wiki:テストデータ生成スクリプト(v2.0)

Version 6 (modified by AMUAMU, 10 years ago) (diff)

--

テストデータ生成スクリプト

EC-CUBE 2.0.x 用のテストデータ生成スクリプトです.

EC-CUBE2.5.x 用最新版はこちら http://svn.ec-cube.net/open_trac/browser/branches/version-2_5-dev/test/createEcCubeData-v25.php

r19692 時点の2.5に対応した更新版を r19693 にて本体側のtestディレクトリに設置しました。

  • 本体側のSC_Queryを利用するようにしました(そのため本体側にコミットしました)。
  • 本体側のMDB2を利用するようにしました。
  • PHP4でも動くようにしました。
  • MySQLでの動作問題を修正しました。大抵の環境であれば何も変えないで動くはずです。
  • 設置するのに適したディレクトリが見当たらないのでtestディレクトリに入れました。問題があれば移動して下さい。

cli 版の PHP を使用し, このスクリプトを実行することにより, テスト用の商品データを自動生成します.

  • 実行時間の計測に PHP5 のみサポートされている関数を使用しています. PHP4 を使用した場合は, 実行時間の計測ができません.
  • Pear::DB に依存していますので, include_path に Pear::DB が必要です.
  • 下記の PHPコードをコピーして, CreateEcCubeData.php というファイル名で保存して下さい.
  • 先頭の #!/usr/local/bin/php というパスを環境に合わせて編集して下さい.
  • define の値を環境に合わせて編集して下さい.

下記も参照

 テストデータ生成スクリプトについて

  • thanx ramrun さん

実行例

 % ./CreateEcCubeData.php

CreateEcCubeData.php

#!/usr/local/bin/php -q
<?php
/*
 * EC-CUBE データ生成スクリプト
 *
 * Copyright(c) 2000-2010 LOCKON CO.,LTD. All Rights Reserved.
 *
 * http://www.lockon.co.jp/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * @auther Kentaro Ohkouchi <ohkouchi@loop-az.jp>
 * @version $Id$
 */

// {{{ requires
require_once("DB.php");

// }}}
// {{{ constants

/** データベース種別 */
define("DB_TYPE", "pgsql");
/** DBホスト */
define("DB_SERVER", "localhost");
/** DBポート */
define("DB_PORT", "5432");
/** DB名 */
define("DB_NAME", "eccube_db");
/** DBユーザー */
define("DB_USER", "eccube_db_user");
/** DBパスワード */
define("DB_PASSWORD", "password");

/** データソース名 */
define ("DEFAULT_DSN",
        DB_TYPE . "://" . DB_USER . ":" . DB_PASSWORD . "@"
                    . DB_SERVER . ":" .DB_PORT . "/" . DB_NAME);

/** 大カテゴリの生成数 */
define("TOP_CATEGORIES_VOLUME", 5);

/** 中カテゴリの生成数 */
define("MIDDLE_CATEGORIES_VOLUME", 2);

/** 小カテゴリの生成数 */
define("SMALL_CATEGORIES_VOLUME", 3);

/** 規格1の生成数 */
define("CLASSCATEGORY1_VOLUME", 1);

/** 規格2の生成数 */
define("CLASSCATEGORY2_VOLUME", 2);

/** 商品の生成数 */
define("PRODUCTS_VOLUME", 100);

// }}}
// {{{ Logic

$objData = new CreateEcCubeData();
$start = microtime(true);
$objData->objQuery->begin();

// カテゴリ生成
$objData->createCategories();
// 規格生成
$objData->createClassData();
// 商品生成
$objData->createProducts();
// 商品と規格の関連づけ
$objData->relateClass();
// 商品とカテゴリの関連づけ
$objData->relateProductsCategories();
//$objData->objQuery->rollback();
$objData->objQuery->commit();
$end = microtime(true);
print("データの生成が完了しました!\n");
printf("所要時間 %f 秒\n", $end - $start);


// }}}
// {{{ classes

/**
 * EC-CUBE のデータを生成する
 */
class CreateEcCubeData {

    /** SC_Query インスタンス */
    var $objQuery;

    /** 大カテゴリID の配列 */
    var $arrCategory1  = array();

    /** 中カテゴリID の配列 */
    var $arrCategory2  = array();

    /** 小カテゴリID の配列 */
    var $arrCategory3  = array();

    /** 規格1 */
    var $arrClassCategory_id1 = array();

    /** 規格2 */
    var $arrClassCategory_id2 = array();

    /**
     * コンストラクタ.
     */
    function CreateEcCubeData() {
        $this->objQuery = new SC_Query();
    }

    /**
     * カテゴリを生成する.
     *
     * 以下のように, ツリー状のカテゴリを生成する
     *
     *  大カテゴリ -- 中カテゴリ -- 小カテゴリ
     *             |             |- 小カテゴリ
     *             |             |- 小カテゴリ
     *             |
     *             |- 中カテゴリ -- 小カテゴリ
     *                            |- 小カテゴリ
     *                            |- 小カテゴリ
     * @return void
     */
    function createCategories() {

        print("カテゴリを生成しています...\n");

        $count = 0;

        // 全カテゴリ共通の値
        $sqlval['creator_id'] = 2;
        $sqlval['create_date'] = "now()";
        $sqlval['update_date'] = "now()";
        $sqlval['del_flg'] = (string) "0";

        // 大カテゴリを生成
        for ($i = 0; $i < TOP_CATEGORIES_VOLUME; $i++) {
            $sqlval['category_name'] = sprintf("Category%d00", $i);
            $sqlval['parent_category_id'] = (string) "0";
            $sqlval['level'] = 1;
            $sqlval['rank'] = $this->lfGetTotalCategoryrank() - $count;

            $this->objQuery->insert("dtb_category", $sqlval);
            $category_id1 = $this->objQuery->currval("dtb_category",
                                                     "category_id");
            $this->arrCategory1[] = $category_id1;
            $count++;
            print(".");

            // 中カテゴリを生成
            for ($j = 0; $j < MIDDLE_CATEGORIES_VOLUME; $j++) {
                $sqlval['category_name'] = sprintf("Category%d%d0", $i,
                                                   $j + MIDDLE_CATEGORIES_VOLUME);
                $sqlval['parent_category_id'] = (string) $category_id1;
                $sqlval['level'] = 2;
                $sqlval['rank'] = $this->lfGetTotalCategoryrank() - $count;

                $this->objQuery->insert("dtb_category", $sqlval);
                $category_id2 = $this->objQuery->currval("dtb_category",
                                                         "category_id");
                $this->arrCategory2[] = $category_id2;
                $count++;
                print(".");

                // 小カテゴリを生成
                for ($k = 0; $k < SMALL_CATEGORIES_VOLUME; $k++) {
                    $sqlval['category_name'] = sprintf("Category%d%d%d",
                                                       $i, $j,
                                                       $k + SMALL_CATEGORIES_VOLUME);
                    $sqlval['parent_category_id'] = (string) $category_id2;
                    $sqlval['level'] = 3;
                    $sqlval['rank'] = $this->lfGetTotalCategoryrank() - $count;

                    $this->objQuery->insert("dtb_category", $sqlval);
                    $category_id3 = $this->objQuery->currval("dtb_category",
                                                             "category_id");
                    $this->arrCategory3[] = $category_id3;
                    $count++;
                    print(".");
                }
            }
        }
        print("\n");
    }

    /**
     * 規格を生成する.
     *
     * @return void
     */
    function createClassData() {
        // 規格データ生成
        print("規格データを生成しています...\n");
        $this->createClass("Size");
        $this->createClass("Color");
        print("\n");

        // 規格分類データ生成
        print("規格分類データを生成しています...\n");

        // 規格1
        for ($i = 0; $i < CLASSCATEGORY1_VOLUME; $i++) {
            $this->createClassCategory($this->arrSize[$i],
                                       $this->arrclass_id[0], "size");
        }

        // 規格2
        for ($i = 0; $i < CLASSCATEGORY2_VOLUME; $i++) {
            $this->createClassCategory($this->arrSize[$i],
                                       $this->arrclass_id[1], "color");
        }

        print("\n");
    }

    /**
     * 商品と規格の関連づけを行う.
     *
     * @return void
     */
    function relateClass() {

        print("商品と規格の関連づけを行います...\n");

        foreach ($this->arrProduct_id as $product_id) {
            $this->createProductsClass($product_id);
        }
        print("\n");
    }

    /**
     * 商品を生成する.
     *
     * @return void
     */
    function createProducts() {

        print("商品を生成しています...\n");
        for ($i = 0; $i < PRODUCTS_VOLUME; $i++) {
            $sqlval['name'] = sprintf("商品%d", $i);
            $sqlval['status'] = 1;
            $sqlval['product_flag'] = "10010";
            $sqlval['point_rate'] = 1;
            $sqlval['comment3'] = "コメント";
            $sqlval['main_list_comment'] = "コメント";
            $sqlval['main_list_image'] = "08311201_44f65122ee5fe.jpg";
            $sqlval['main_comment'] = "コメント";
            $sqlval['main_image'] = "08311202_44f6515906a41.jpg";
            $sqlval['main_large_image'] = "08311203_44f651959bcb5.jpg";
            $sqlval['sub_comment1'] = "コメント";
            $sqlval['del_flg'] = (string) "0";
            $sqlval['creator_id'] = 2;
            $sqlval['create_date'] = "now()";
            $sqlval['update_date'] = "now()";
            $sqlval['deliv_date_id'] = 2;

            $this->objQuery->insert("dtb_products", $sqlval);
            $this->arrProduct_id[] = $this->objQuery->currval("dtb_products",
                                                              "product_id");
            print("*");
        }
    }

    /**
     * 規格を生成する.
     *
     * @param $class_name string 規格名
     * @return void
     */
    function createClass($class_name) {
        $sqlval['name'] = $class_name;
        $sqlval['status'] = null;
        $sqlval['rank'] = "~(SELECT CASE
                                      WHEN max(rank) + 1 IS NULL THEN 1
                                      ELSE max(rank) + 1
                                    END
                               FROM dtb_class
                              WHERE del_flg = 0),";
        $sqlval['creator_id'] = 2;
        $sqlval['update_date'] = "now()";
        $sqlval['del_flg'] = (string) "0";
        $sqlval['product_id'] = null;

        $this->objQuery->insert("dtb_class", $sqlval);

        // class_idを取得
        $this->arrclass_id[] = $this->objQuery->currval("dtb_class", "class_id");
        print("+");
    }

    /**
     * 規格分類を生成する.
     *
     * @param $classcategory_name string 規格名
     * @return void
     */
    function createClassCategory($classcategory_name, $class_id, $class_name) {
        $sqlval['name'] = $classcategory_name;
        $sqlval['class_id'] = $class_id;
        $sqlval['status'] = null;
        $sqlval['rank'] = sprintf("~(SELECT CASE
                                              WHEN max(rank) + 1 IS NULL THEN 1
                                              ELSE max(rank) + 1
                                            END
                                       FROM dtb_classcategory
                                      WHERE del_flg = 0
                                        AND class_id = %d),", $class_id);
        $sqlval['creator_id'] = 2;
        $sqlval['create_date'] = "now()";
        $sqlval['update_date'] = "now()";
        $sqlval['del_flg'] = (string) "0";

        $this->objQuery->insert("dtb_classcategory", $sqlval);

        switch ($class_name) {
        case "size":
            $this->arrClassCategory_id1[] =
                $this->objQuery->currval("dtb_classcategory",
                                         "classcategory_id");
            break;

        case "color":
            $this->arrClassCategory_id2[] =
                $this->objQuery->currval("dtb_classcategory",
                                         "classcategory_id");
            break;
        default:
        }
        print("+");
    }

    /**
     * 商品規格を生成する.
     *
     * @param integer $product_id 商品ID
     * @return void
     */
    function createProductsClass($product_id) {

        printf("商品ID %d の商品規格を生成しています...\n", $product_id);

        $sqlval['product_id'] = $product_id;
        $sqlval['stock_unlimited'] = 1;
        $sqlval['price01'] = 1000;
        $sqlval['price02'] = 2000;
        $sqlval['creator_id'] = 2;
        $sqlval['create_date'] = "now()";
        $sqlval['update_date'] = "now()";

        $count = 0;
        foreach ($this->arrClassCategory_id1 as $classCategory_id1) {
            $sqlval['classcategory_id1'] = $classCategory_id1;

            foreach ($this->arrClassCategory_id2 as $classCategory_id2) {
                $sqlval['classcategory_id2'] = $classCategory_id2;
                $sqlval['product_code'] = sprintf("商品コード%d", $count);

                $this->objQuery->insert("dtb_products_class", $sqlval);
                $count++;
                print("#");
            }
        }
        print("\n");
    }

    /**
     * 商品とカテゴリの関連づけを行う.
     *
     * @return void
     */
    function relateProductsCategories() {

        print("商品とカテゴリの関連づけを行います...\n");
        $this->createProductsCategories($this->arrCategory1, "大カテゴリ");
        $this->createProductsCategories($this->arrCategory2, "中カテゴリ");
        $this->createProductsCategories($this->arrCategory3, "小カテゴリ");
    }

    /**
     * 商品カテゴリを生成する.
     *
     * @param array $arrCategory_id カテゴリID の配列
     * @return void
     */
    function createProductsCategories($arrCategory_id, $category_name) {

        $count = 0;
        printf("%s の商品カテゴリを生成しています...\n", $category_name);
        foreach ($arrCategory_id as $category_id) {
            $sqlval['category_id'] = $category_id;

            foreach($this->arrProduct_id as $product_id) {
                $sqlval['product_id'] = $product_id;
                $sqlval['rank'] = $count;

                $this->objQuery->insert("dtb_product_categories", $sqlval);
                $count++;
                print("$");
            }
        }
        print("\n");
    }

    /** 規格1 */
    var $arrSize = array("m11(29cm)"
                         ,"m10 1/2(28.5cm)"
                         ,"m10(28cm)"
                         ,"m9 1/2(27.5cm)"
                         ,"m9(27cm)"
                         ,"m8 1/2(26.5cm)"
                         ,"m8(26cm)"
                         ,"43"
                         ,"42"
                         ,"41"
                         ,"43(27.0cm?27.5cm)"
                         ,"42(26.5cm?27.0cm)"
                         ,"37(ladies 23.5?24cm)"
                         ,"42(約27.5cm)"
                         ,"41(約26.5cm)"
                         ,"W36"
                         ,"W34"
                         ,"W32"
                         ,"43"
                         ,"42"
                         ,"41"
                         ,"m11"
                         ,"m10"
                         ,"m9.5"
                         ,"m9"
                         ,"m8"
                         ,"FREE"
                         ,"XS"
                         ,"S"
                         ,"M"
                         ,"L"
                         ,"XL"
                         ,"25-27"
                         ,"27-29"
                         ,"W28"
                         ,"W29"
                         ,"W30"
                         ,"W31"
                         ,"W32"
                         ,"W33"
                         ,"W34"
                         ,"W35"
                         ,"W36"
                         ,"4"
                         ,"6"
                         ,"8"
                         ,"10"
                         ,"12"
                         ,"10cm"
                         ,"12cm"
                         ,"14cm"
                         ,"16cm"
                         ,"18cm"
                         ,"20cm"
                         ,"22cm"
                         ,"24cm"
                         ,"26cm"
                         ,"28cm"
                         ,"30cm"
                         ,"32cm"
                         ,"34cm"
                         ,"36cm"
                         ,"38cm"
                         ,"40cm"
                         ,"10g"
                         ,"20g"
                         ,"30g"
                         ,"40g"
                         ,"50g"
                         ,"60g"
                         ,"70g"
                         ,"80g"
                         ,"90g"
                         ,"100g"
                         ,"110g"
                         ,"120g"
                         ,"130g"
                         ,"140g"
                         ,"150g"
                         ,"160g"
                         ,"170g"
                         ,"180g"
                         ,"190g"
                         ,"200g"
                         ,"8inch"
                         ,"10inch"
                         ,"12inch"
                         ,"14inch"
                         ,"16inch"
                         ,"18inch"
                         ,"20inch"
                         ,"22inch"
                         ,"24inch"
                         ,"26inch"
                         ,"28inch"
                         ,"30inch"
                         ,"32inch"
                         ,"34inch"
                         ,"36inch"
                         ,"38inch"
                    );

    /** 規格2 */
    var $arrColor = array("white"
                         ,"whitesmoke"
                         ,"snow"
                         ,"ghostwhite"
                         ,"mintcream"
                         ,"azure"
                         ,"ivory"
                         ,"floralwhite"
                         ,"aliceblue"
                         ,"lavenderblush"
                         ,"seashell"
                         ,"honeydew"
                         ,"lightyellow"
                         ,"oldlace"
                         ,"cornsilk"
                         ,"linen"
                         ,"lemonchiffon"
                         ,"lavender"
                         ,"beige"
                         ,"lightgoldenrodyellow"
                         ,"mistyrose"
                         ,"papayawhip"
                         ,"antiquewhite"
                         ,"lightcyan"
                         ,"cyan"
                         ,"aqua"
                         ,"darkcyan"
                         ,"teal"
                         ,"darkslategray"
                         ,"turquoise"
                         ,"paleturquoise"
                         ,"mediumturquoise"
                         ,"aquamarine"
                         ,"gainsboro"
                         ,"lightgray"
                         ,"silver"
                         ,"darkgray"
                         ,"gray"
                         ,"dimgray"
                         ,"black"
                         ,"powderblue"
                         ,"lightblue"
                         ,"lightskyblue"
                         ,"skyblue"
                         ,"darkturquoise"
                         ,"deepskyblue"
                         ,"dodgerblue"
                         ,"royalblue"
                         ,"cornflowerblue"
                         ,"cadetblue"
                         ,"lightsteelblue"
                         ,"steelblue"
                         ,"lightslategray"
                         ,"slategray"
                         ,"blue"
                         ,"mediumblue"
                         ,"darkblue"
                         ,"navy"
                         ,"midnightblue"
                         ,"lightsalmon"
                         ,"darksalmon"
                         ,"salmon"
                         ,"tomato"
                         ,"lightcoral"
                         ,"coral"
                         ,"crimson"
                         ,"red"
                         ,"mediumorchid"
                         ,"mediumpurple"
                         ,"mediumslateblue"
                         ,"slateblue"
                         ,"blueviolet"
                         ,"darkviolet"
                         ,"darkorchid"
                         ,"darkslateblue"
                         ,"darkorchid"
                         ,"thistle"
                         ,"plum"
                         ,"violet"
                         ,"magenta"
                         ,"fuchsia"
                         ,"darkmagenta"
                         ,"purple"
                         ,"palegreen"
                         ,"lightgreen"
                         ,"lime"
                         ,"limegreen"
                         ,"forestgreen"
                         ,"green"
                         ,"darkgreen"
                         ,"greenyellow"
                         ,"chartreuse"
                         ,"lawngreen"
                         ,"yellowgreen"
                         ,"olivedrab"
                         ,"darkolivegreen"
                         ,"mediumaquamarine"
                         ,"mediumspringgreen"
                         ,"springgreen"
                         ,"darkseagreen"
                     );

    /**
    * 総カテゴリー数を計算し、dtb_categoryに代入するrankに使う
    */
    function lfGetTotalCategoryrank(){
        $TotalCategoryrank = (TOP_CATEGORIES_VOLUME * MIDDLE_CATEGORIES_VOLUME * SMALL_CATEGORIES_VOLUME) + (MIDDLE_CATEGORIES_VOLUME * TOP_CATEGORIES_VOLUME) + TOP_CATEGORIES_VOLUME;
    return $TotalCategoryrank;
    }

}

/**
 * クエリを生成して実行する.
 *
 * (EC-CUBE からの移植)
 */
class SC_Query {
    var $option;
    var $where;
    var $conn;
    var $groupby;
    var $order;

    // コンストラクタ
    /*
        $err_disp:エラー表示を行うか
        $new:新規に接続を行うか
     */
    function SC_Query($dsn = "", $err_disp = true, $new = false) {
        $this->conn = new SC_DbConn($dsn, $err_disp, $new);
        $this->where = "";
        return $this->conn;
    }

    // エラー判定
    function isError() {
        if(PEAR::isError($this->conn->conn)) {
            return true;
        }
        return false;
    }

    // COUNT文の実行
    function count($table, $where = "", $arrval = array()) {
        if(strlen($where) <= 0) {
            $sqlse = "SELECT COUNT(*) FROM $table";
        } else {
            $sqlse = "SELECT COUNT(*) FROM $table WHERE $where";
        }
        // カウント文の実行
        $ret = $this->conn->getOne($sqlse, $arrval);
        return $ret;
    }

    function select($col, $table, $where = "", $arrval = array()){
        $sqlse = $this->getsql($col, $table, $where);
        // DBに依存した SQL へ変換
        $dbFactory = SC_DB_DBFactory::getInstance();
        $sqlse = $dbFactory->sfChangeMySQL($sqlse);
        $ret = $this->conn->getAll($sqlse, $arrval);
        return $ret;
    }

    function getLastQuery($disp = true) {
        $sql = $this->conn->conn->last_query;
        if($disp) {
            print($sql.";<br />\n");
        }
        return $sql;
    }

    function commit() {
        $this->conn->query("COMMIT");
    }

    function begin() {
        $this->conn->query("BEGIN");
    }

    function rollback() {
        $this->conn->query("ROLLBACK");
    }

    function exec($str, $arrval = array()) {
        $this->conn->query($str, $arrval);
    }

    function autoselect($col, $table, $arrwhere = array(), $arrcon = array()) {
        $strw = "";
        $find = false;
        foreach ($arrwhere as $key => $val) {
            if(strlen($val) > 0) {
                if(strlen($strw) <= 0) {
                    $strw .= $key ." LIKE ?";
                } else if(strlen($arrcon[$key]) > 0) {
                    $strw .= " ". $arrcon[$key]. " " . $key ." LIKE ?";
                } else {
                    $strw .= " AND " . $key ." LIKE ?";
                }

                $arrval[] = $val;
            }
        }

        if(strlen($strw) > 0) {
            $sqlse = "SELECT $col FROM $table WHERE $strw ".$this->option;
        } else {
            $sqlse = "SELECT $col FROM $table ".$this->option;
        }
        $ret = $this->conn->getAll($sqlse, $arrval);
        return $ret;
    }

    function getall($sql, $arrval = array()) {
        $ret = $this->conn->getAll($sql, $arrval);
        return $ret;
    }

    function getsql($col, $table, $where) {
        if($where != "") {
            // 引数の$whereを優先して実行する。
            $sqlse = "SELECT $col FROM $table WHERE $where " . $this->groupby . " " . $this->order . " " . $this->option;
        } else {
            if($this->where != "") {
                    $sqlse = "SELECT $col FROM $table WHERE $this->where " . $this->groupby . " " . $this->order . " " . $this->option;
                } else {
                    $sqlse = "SELECT $col FROM $table " . $this->groupby . " " . $this->order . " " . $this->option;
            }
        }
        return $sqlse;
    }

    function setoption($str) {
        $this->option = $str;
    }

    function setlimitoffset($limit, $offset = 0, $return = false) {
        if (is_numeric($limit) && is_numeric($offset)){

            $option = " LIMIT " . $limit;
            $option.= " OFFSET " . $offset;

            if($return){
                return $option;
            }else{
                $this->option.= $option;
            }
        }
    }

    function setgroupby($str) {
        $this->groupby = "GROUP BY " . $str;
    }

    function andwhere($str) {
        if($this->where != "") {
            $this->where .= " AND " . $str;
        } else {
            $this->where = $str;
        }
    }

    function orwhere($str) {
        if($this->where != "") {
            $this->where .= " OR " . $str;
        } else {
            $this->where = $str;
        }
    }

    function setwhere($str) {
        $this->where = $str;
    }

    function setorder($str) {
        $this->order = "ORDER BY " . $str;
    }


    function setlimit($limit){
        if ( is_numeric($limit)){
            $this->option = " LIMIT " .$limit;
        }
    }

    function setoffset($offset) {
        if ( is_numeric($offset)){
            $this->offset = " OFFSET " .$offset;
        }
    }


    // INSERT文の生成・実行
    // $table   :テーブル名
    // $sqlval  :列名 => 値の格納されたハッシュ配列
    function insert($table, $sqlval) {
        $strcol = '';
        $strval = '';
        $find = false;

        if(count($sqlval) <= 0 ) return false;

        foreach ($sqlval as $key => $val) {
            $strcol .= $key . ',';
            if(eregi("^Now\(\)$", $val)) {
                $strval .= 'Now(),';
            // 先頭に~があるとプレースホルダーしない。
            } else if(ereg("^~", $val)) {
                $strval .= ereg_replace("^~", "", $val);
            } else {
                $strval .= '?,';
                if($val != ""){
                    $arrval[] = $val;
                } else {
                    $arrval[] = NULL;
                }
            }
            $find = true;
        }
        if(!$find) {
            return false;
        }
        // 文末の","を削除
        $strcol = ereg_replace(",$","",$strcol);
        // 文末の","を削除
        $strval = ereg_replace(",$","",$strval);
        $sqlin = "INSERT INTO $table(" . $strcol. ") VALUES (" . $strval . ")";

        // INSERT文の実行
        $ret = $this->conn->query($sqlin, $arrval);

        return $ret;
    }

        // INSERT文の生成・実行
    // $table   :テーブル名
    // $sqlval  :列名 => 値の格納されたハッシュ配列
    function fast_insert($table, $sqlval) {
        $strcol = '';
        $strval = '';
        $find = false;

        foreach ($sqlval as $key => $val) {
                $strcol .= $key . ',';
                if($val != ""){
                    $eval = pg_escape_string($val);
                    $strval .= "'$eval',";
                } else {
                    $strval .= "NULL,";
                }
                $find = true;
        }
        if(!$find) {
            return false;
        }
        // 文末の","を削除
        $strcol = ereg_replace(",$","",$strcol);
        // 文末の","を削除
        $strval = ereg_replace(",$","",$strval);
        $sqlin = "INSERT INTO $table(" . $strcol. ") VALUES (" . $strval . ")";

        // INSERT文の実行
        $ret = $this->conn->query($sqlin);

        return $ret;
    }


    // UPDATE文の生成・実行
    // $table   :テーブル名
    // $sqlval  :列名 => 値の格納されたハッシュ配列
    // $where   :WHERE文字列
    function update($table, $sqlval, $where = "", $arradd = "", $addcol = "") {
        $strcol = '';
        $strval = '';
        $find = false;
        foreach ($sqlval as $key => $val) {
            if(eregi("^Now\(\)$", $val)) {
                $strcol .= $key . '= Now(),';
            // 先頭に~があるとプレースホルダーしない。
            } else if(ereg("^~", $val)) {
                $strcol .= $key . "=" . ereg_replace("^~", "", $val) . ",";
            } else {
                $strcol .= $key . '= ?,';
                if($val != ""){
                    $arrval[] = $val;
                } else {
                    $arrval[] = NULL;
                }
            }
            $find = true;
        }
        if(!$find) {
            return false;
        }

        if($addcol != "") {
            foreach($addcol as $key => $val) {
                $strcol .= "$key = $val,";
            }
        }

        // 文末の","を削除
        $strcol = ereg_replace(",$","",$strcol);
        // 文末の","を削除
        $strval = ereg_replace(",$","",$strval);

        if($where != "") {
            $sqlup = "UPDATE $table SET $strcol WHERE $where";
        } else {
            $sqlup = "UPDATE $table SET $strcol";
        }

        if(is_array($arradd)) {
            // プレースホルダー用に配列を追加
            foreach($arradd as $val) {
                $arrval[] = $val;
            }
        }

        // INSERT文の実行
        $ret = $this->conn->query($sqlup, $arrval);
        return $ret;
    }

    // MAX文の実行
    function max($table, $col, $where = "", $arrval = array()) {
        if(strlen($where) <= 0) {
            $sqlse = "SELECT MAX($col) FROM $table";
        } else {
            $sqlse = "SELECT MAX($col) FROM $table WHERE $where";
        }
        // MAX文の実行
        $ret = $this->conn->getOne($sqlse, $arrval);
        return $ret;
    }

    // MIN文の実行
    function min($table, $col, $where = "", $arrval = array()) {
        if(strlen($where) <= 0) {
            $sqlse = "SELECT MIN($col) FROM $table";
        } else {
            $sqlse = "SELECT MIN($col) FROM $table WHERE $where";
        }
        // MIN文の実行
        $ret = $this->conn->getOne($sqlse, $arrval);
        return $ret;
    }

    // 特定のカラムの値を取得
    function get($table, $col, $where = "", $arrval = array()) {
        if(strlen($where) <= 0) {
            $sqlse = "SELECT $col FROM $table";
        } else {
            $sqlse = "SELECT $col FROM $table WHERE $where";
        }
        // SQL文の実行
        $ret = $this->conn->getOne($sqlse, $arrval);
        return $ret;
    }

    function getone($sql, $arrval = array()) {
        // SQL文の実行
        $ret = $this->conn->getOne($sql, $arrval);
        return $ret;

    }

    // 一行を取得
    function getrow($table, $col, $where = "", $arrval = array()) {
        if(strlen($where) <= 0) {
            $sqlse = "SELECT $col FROM $table";
        } else {
            $sqlse = "SELECT $col FROM $table WHERE $where";
        }
        // SQL文の実行
        $ret = $this->conn->getRow($sqlse, $arrval);

        return $ret;
    }

    // 1列取得
    function getCol($table, $col, $where = "", $arrval = array()) {
        if (strlen($where) <= 0) {
            $sqlse = "SELECT $col FROM $table";
        } else {
            $sqlse = "SELECT $col FROM $table WHERE $where";
        }
        // SQL文の実行
        return $this->conn->getCol($sqlse, $col, $arrval);
    }

    // レコードの削除
    function delete($table, $where = "", $arrval = array()) {
        if(strlen($where) <= 0) {
            $sqlde = "DELETE FROM $table";
        } else {
            $sqlde = "DELETE FROM $table WHERE $where";
        }
        $ret = $this->conn->query($sqlde, $arrval);
        return $ret;
    }

    function nextval($table, $colname) {
        $sql = "";
        // postgresqlとmysqlとで処理を分ける
        if (DB_TYPE == "pgsql") {
            $seqtable = $table . "_" . $colname . "_seq";
            $sql = "SELECT NEXTVAL('$seqtable')";
        }else if (DB_TYPE == "mysql") {
            $sql = "SELECT last_insert_id();";
        }
        $ret = $this->conn->getOne($sql);

        return $ret;
    }

    function currval($table, $colname) {
        $sql = "";
        if (DB_TYPE == "pgsql") {
            $seqtable = $table . "_" . $colname . "_seq";
            $sql = "SELECT CURRVAL('$seqtable')";
        }else if (DB_TYPE == "mysql") {
            $sql = "SELECT last_insert_id();";
        }
        $ret = $this->conn->getOne($sql);

        return $ret;
    }

    function setval($table, $colname, $data) {
        $sql = "";
        if (DB_TYPE == "pgsql") {
            $seqtable = $table . "_" . $colname . "_seq";
            $sql = "SELECT SETVAL('$seqtable', $data)";
            $ret = $this->conn->getOne($sql);
        }else if (DB_TYPE == "mysql") {
            $sql = "ALTER TABLE $table AUTO_INCREMENT=$data";
            $ret = $this->conn->query($sql);
        }

        return $ret;
    }

    function query($n ,$arr = "", $ignore_err = false){
        $result = $this->conn->query($n, $arr, $ignore_err);
        return $result;
    }

    // auto_incrementを取得する
    function get_auto_increment($table_name){
        // ロックする
        $this->query("LOCK TABLES $table_name WRITE");

        // 次のIncrementを取得
        $arrRet = $this->getAll("SHOW TABLE STATUS LIKE ?", array($table_name));
        $auto_inc_no = $arrRet[0]["Auto_increment"];

        // 値をカウントアップしておく
        $this->conn->query("ALTER TABLE $table_name AUTO_INCREMENT=?" , $auto_inc_no + 1);

        // 解除する
        $this->query('UNLOCK TABLES');

        return $auto_inc_no;
    }
}


$objDbConn = "";

/**
 * コネクションを取得する.
 *
 * (EC-CUBE からの移植)
 */
class SC_DbConn{

    var $conn;
    var $dump;
    var $result;
    var $includePath;
    var $error_mail_to;
    var $error_mail_title;
    var $dsn;
    var $err_disp = true;
    var $dbFactory;


    // コンストラクタ
    function SC_DbConn($dsn = "", $err_disp = true, $new = false){

        // Debugモード指定
        $options['debug'] = true;
        // 既に接続されていないか、新規接続要望の場合は接続する。
        if(!isset($objDbConn->connection) || $new) {
            if($dsn != "") {
                $objDbConn = DB::connect($dsn, $options);
                $this->dsn = $dsn;
            } else {
                if(defined('DEFAULT_DSN')) {
                    $objDbConn = DB::connect(DEFAULT_DSN, $options);
                    $this->dsn = DEFAULT_DSN;
                } else {
                    return;
                }
            }
        }

        $this->conn = $objDbConn;
        $this->error_mail_to = DB_ERROR_MAIL_TO;
        $this->error_mail_title = DB_ERROR_MAIL_SUBJECT;
        $this->err_disp = $err_disp;
    }

    // クエリの実行
    function query($n ,$arr = "", $ignore_err = false){

        if ( $arr ) {
            $result = $this->conn->query($n, $arr);
        } else {
            $result = $this->conn->query($n);
        }

        if ($this->conn->isError($result) && !$ignore_err){
            $this->send_err_mail ($result, $n);
        }

        $this->result = $result;
        return $this->result;
    }

    // 一件のみ取得
    function getOne($n, $arr = ""){

        if ( $arr ) {
            $result = $this->conn->getOne($n, $arr);
        } else {
            $result = $this->conn->getOne($n);
        }
        if ($this->conn->isError($result)){
            $this->send_err_mail ($result ,$n);
        }
        $this->result = $result;

        return $this->result;
    }

    function getRow($n, $arr = ""){

        if ( $arr ) {
            $result = $this->conn->getRow($n, $arr);
        } else {
            $result = $this->conn->getRow($n);
        }
        if ($this->conn->isError($result)){
            $this->send_err_mail ($result ,$n);
        }
        $this->result = $result;
        return $this->result;
    }

    function getCol($n, $col, $arr = "") {

        if ($arr) {
            $result = $this->conn->getCol($n, $col, $arr);
        } else {
            $result = $this->conn->getCol($n, $col);
        }
        if ($this->conn->isError($result)) {
            $this->send_err_mail($result, $n);
        }
        $this->result = $result;
        return $this->result;
    }

    // SELECT文の実行結果を全て取得
    function getAll($n, $arr = ""){


        if(PEAR::isError($this->conn)) {
            if(ADMIN_MODE){
                SC_Utils_Ex::sfErrorHeader("DBへの接続に失敗しました。:" . $this->dsn);
            }else{
                SC_Utils_Ex::sfErrorHeader("DBへの接続に失敗しました。:");
            }
            return 0;
        }

        if ( $arr ){
            $result = $this->conn->getAll($n, $arr, DB_FETCHMODE_ASSOC);
        } else {
            $result = $this->conn->getAll($n, DB_FETCHMODE_ASSOC);
        }

        if ($this->conn->isError($result)){
            $this->send_err_mail ($result, $n);
        }
        $this->result = $result;

        return $this->result;
    }

    function autoExecute($table_name, $fields_values, $sql_where = null){

        if ( $sql_where ) {
            $result = $this->conn->autoExecute( $table_name, $fields_values, DB_AUTOQUERY_UPDATE, $sql_where);
        } else {
            $result = $this->conn->autoExecute( $table_name, $fields_values, DB_AUTOQUERY_INSERT);
        }

        if ($this->conn->isError($result)){
            $this->send_err_mail ($result, $n);
        }
        $this->result = $result;
        return $this->result;
    }


    function prepare($n){
        global $sql;
        $sql = $n;
        $result = $this->conn->prepare($n);
        $this->result = $result;
        return $this->result;
    }

    function execute($n, $obj){
        global $sql;
        $sql = $n;
        $result = $this->conn->execute($n, $obj);
        $this->result = $result;
        return $this->result;
    }

    function reset(){
        $this->conn->disconnect();
    }

    function send_err_mail($result, $sql){
        $url = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

        $errmsg = $url."\n\n";
        $errmsg.= "SERVER_ADDR:" . $_SERVER['SERVER_ADDR'] . "\n";
        $errmsg.= "REMOTE_ADDR:" . $_SERVER['REMOTE_ADDR'] . "\n";
        $errmsg.= "USER_AGENT:" . $_SERVER['HTTP_USER_AGENT'] . "\n\n";
        $errmsg.= $sql . "\n";
        $errmsg.= $result->message . "\n\n";
        $errmsg.= $result->userinfo . "\n\n";

        $arrRbacktrace = array_reverse($result->backtrace);

        foreach($arrRbacktrace as $backtrace) {
            if($backtrace['class'] != "") {
                $func = $backtrace['class'] . "->" . $backtrace['function'];
            } else {
                $func = $backtrace['function'];
            }

            $errmsg.= $backtrace['file'] . " " . $backtrace['line'] . ":" . $func . "\n";
        }

        print('<pre>');
        //print_r(htmlspecialchars($errmsg, ENT_QUOTES));
        print_r($errmsg);
        print('</pre>');
        exit();
    }

}

?>

Attachments