<?php
/* SVN FILE: $Id: SQLite.php 338 2008-05-11 01:43:22Z bb_yujiro $ */
/**
 * rkt_manip(ulation).php SQLiteドライバ
 *
 * PHP versions 5
 *
 *      hitSuji : Social Network Service <http://rakuto.net/rktSNS/>
 *      Copyright (c) 2007 Yujiro Takahashi
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 338 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-05-11 10:43:22 +0900 (日, 11 5 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * SQLiteドライバクラス
 *
 * @category        Model::Manipulation
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 338 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-05-11 10:43:22 +0900 (日, 11 5 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */
class Model_Manip_SQLite
{
    /**
     * DB接続オジェクト
     * @var object
     */
    private $_objdb = null;

    /**
     * テーブル名
     * @var string
     */
    private $_tbl_name = '';

    /**
     * プライマリキー
     * @var array
     */
    private $_primary = array();

    /**
     * コンストラクタ
     *
     * @access public
     * @param string $tbl_name テーブル名
     */
    public function __construct($tbl_name='')
    {
        $this->_objdb = RKT_DB::getInstance();

        $this->_tbl_name = $tbl_name;
    }

    /**
     * テーブル名の設定
     *
     * @access public
     * @param string $tbl_name
     * @return void
     */
    public function setTableName($tbl_name)
    {
        $this->_tbl_name = $tbl_name;
    }

    /**
     * プライマリキーの取得
     *
     * @access public
     * @return string
     */
    public function getPrimaryKey()
    {
        return $this->_primary['key'];
    }

    /**
     * 全テーブル名の取得
     *
     * @access public
     * @return array
     */
    public function getTables()
    {
        $sql =
            'SELECT '.
                'name '.
            'FROM '.
                'sqlite_master '.
            'WHERE '.
                "type = 'table'";
        $stmt = $this->_objdb->prepare($sql); 
        $stmt->execute(); 
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $list = array();
        foreach ($result as $value){
            $list[] = $value['name'];
        }

        return $list;
    }

    /**
     * 項目情報の解析
     *
     * @access public
     * @param array $skip
     * @return array
     */
    public function parseColumns($skip=array())
    {
        $result = null;
        $sql= 'PRAGMA table_info('.$this->_tbl_name.')';
        $stmt = $this->_objdb->prepare($sql); 
        $stmt->execute(); 

        $validates = array();
        $cols = array();
        while ($value = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $key  = $value['name'];
            $parse = $this->_parseType($value['type'],$key);

            $infos = array(
                'type'=>    $parse['type'],
                'pdo_type'=>$parse['pdo_type'],
                'option'=>  $parse['option'],
                'default'=> trim($value['dflt_value'], "'"),
                'required'=>$this->_parseRequired($value['notnull']),
                'effect'=>  array('RKT_validate', $parse['effect']),
            );

            /* プライマリキーは別扱い */
            if ($this->_isPrimaryKey($value['pk'])){
                $this->_primary = array(
                    'key'=>  $key,
                    'info'=> $infos
                );
            } else {
                if (!in_array($key,$skip)){
                    $validates[$key] = $infos;
                }
            } // if (!$this->catch_primary_key($value['Key']))
        }

        return $validates;
    }

    /**
     * フィールドの型を解析
     *
     * @access private
     * @param string $subject
     * @param string $option
     * @return array
     */
    private function _parseType($subject, $field)
    {
        $type     = 'string';
        $pdo_type = 'PDO::PARAM_STR';
        $option   = null;
        $effect   = 'multiStripTags';
        $size     = 8000;

        if (preg_match('/\d+/i', $subject,$matchs)){
            $size = $matchs[0];
        }

        /* 型名から設定 */
        if (preg_match('/varchar/i', $subject)){
            $type = 'string';
            $option = array(
                'max_length'=>$size
            );
        } else if (preg_match('/int/i', $subject)){
            $type = 'number';
            $pdo_type = 'PDO::PARAM_INT';
        } else if (preg_match('/text/i', $subject)){
            $type = 'string';
            $option = array(
                'max_length'=>$size
            );
            $effect   = 'multiStripJavaScript';
        } else if (preg_match('/date/i', $subject)){
            $type = 'date';
            $option = array(
                'format'=> '%Y-%n-%d'
            );
        } else if (preg_match('/timestamp/i', $subject)){
            $type = 'date';
            $option = array(
                'format'=> '%Y-%n-%d %H:%i:%s'
            );
        } else if (preg_match('/float/i', $subject)){
            $type = 'number';
            $pdo_type = 'PDO::PARAM_INT';
            $option = array(
                'decimal'=>'.'
            );
        } else if (preg_match('/double/i', $subject)){
            $type = 'number';
            $pdo_type = 'PDO::PARAM_INT';
            $option = array(
                'decimal'=>'.'
            );
        } else if (preg_match('/blob/i', $subject)){
            $type = 'string';
            $pdo_type = 'PDO::PARAM_LOB';
            $option = array(
                'max_length'=>$size
            );
        }
        
        /* フィールド名から設定 */
        if (preg_match('/email/i', $field)){
            $type = 'email';
        } else if (preg_match('/url/i', $field)){
            $type = 'uri';
            $pdo_type = 'PDO::PARAM_STR';
        } else if (preg_match('/^html/i', $field)){
            $type = 'string';
            $option = array(
                'max_length'=>$size
            );
            $effect   = 'multiStripSlashes';
        } else if (preg_match('/postal/i', $field)){
            $type = 'string';
            $option = array(
                'format'=>'\d+[-]*\d+'
            );
        } else if (preg_match('/phone/i', $field)){
            $type = 'string';
            $option = array(
                'format'=>'\d+[-]*\d+[-]*\d+'
            );
        } else if (preg_match('/fax/i', $field)){
            $type = 'string';
            $option = array(
                'format'=>'\d+[-]*\d+[-]*\d+'
            );
        } else if (preg_match('/password/i', $field)){
            $type = 'string';
            $option = array(
                'format'=> '\w+',
                'min_length'=>4,
                'max_length'=>$size
            );
        }

        return array('type'=>$type, 'pdo_type'=>$pdo_type, 'option'=>$option, 'effect'=>$effect);
    }

    /**
     * 必須項目設定の解析
     *
     * @access private
     * @param string $subject
     * @return boolean
     */
    private function _parseRequired($subject)
    {
        if (empty($subject)){
            return false;
        }
        return true;
    }

    /**
     * プライマリキーの判定
     *
     * @access private
     * @param string $subject
     * @return boolean
     */
    private function _isPrimaryKey($subject)
    {
        if (empty($subject)){
            return false;
        }
        return true;
    }
} // Model_Manip_SQLiteの終了
?>