Esempio n. 1
0
 public static function getConnection()
 {
     if (!extension_loaded(__DBTYPE__)) {
         throw new Exception("php does not have database exstention for : " . __DBTYPE__);
     }
     if (!class_exists('Creole')) {
         throw new Exception("Could not find Creole Database Abstraction Layer in php_includes");
     }
     $dsn = array('phptype' => __DBTYPE__, 'hostspec' => __DBHOST__, 'username' => __DBUSR__, 'password' => __DBUSERPW__, 'database' => __DBNAME__);
     return Creole::getConnection($dsn);
 }
 /**
  * Test an ASSOC fetch with a connection that has the Creole::NO_ASSOC_LOWER flag set.
  */
 public function testFetchmodeAssocNoChange()
 {
     $exch = DriverTestManager::getExchange('ResultSetTest.ALL_RECORDS');
     $conn2 = Creole::getConnection(DriverTestManager::getDSN(), Creole::NO_ASSOC_LOWER);
     DriverTestManager::initDb($conn2);
     $rs = $conn2->executeQuery($exch->getSql(), ResultSet::FETCHMODE_ASSOC);
     $rs->next();
     $keys = array_keys($rs->getRow());
     $this->assertEquals("PRODUCTID", $keys[0], 0, "Expected to find uppercase column name for Oracle.");
     $rs->close();
 }
Esempio n. 3
0
 /**
  * Constructor
  *
  * Mail_Queue_Container_creole()
  *
  * @param mixed $options    An associative array of connection option.
  *
  * @access public
  */
 function Mail_Queue_Container_creole($options)
 {
     if (!is_array($options) || !isset($options['dsn']) && !isset($options['connection'])) {
         $this->constructor_error = new Mail_Queue_Error(MAILQUEUE_ERROR_NO_OPTIONS, $this->pearErrorMode, E_USER_ERROR, __FILE__, __LINE__, 'No dns specified!');
         return;
     }
     if (isset($options['mail_table'])) {
         $this->mail_table = $options['mail_table'];
     }
     if (!empty($options['pearErrorMode'])) {
         $this->pearErrorMode = $options['pearErrorMode'];
     }
     try {
         $this->db = isset($options['connection']) ? $options['connection'] : Creole::getConnection($options['dsn']);
     } catch (SQLException $e) {
         $this->constructor_error = new Mail_Queue_Error(MAILQUEUE_ERROR_CANNOT_CONNECT, $this->pearErrorMode, E_USER_ERROR, __FILE__, __LINE__, 'CREOLE::connect failed: ' . $e->getMessage());
         return;
     }
     $this->setOption();
 }
 /**
  * Constructor
  */
 public function CreoleSessionContainer()
 {
     $this->conn = Creole::getConnection(Registry::get('__configurator')->getDatabaseDsn());
     CreoleSessionContainer::$lifetime = ini_get('session.gc_maxlifetime');
 }
 /**
  * Establishes a Creole database connection
  *
  * @return     object The connection
  */
 protected function getConnection()
 {
     // Attemtp to connect to a database.
     $this->dsn = Creole::parseDSN($this->dbUrl);
     if ($this->dbUser) {
         $this->dsn["username"] = $this->dbUser;
     }
     if ($this->dbPassword) {
         $this->dsn["password"] = $this->dbPassword;
     }
     if ($this->dbDriver) {
         Creole::registerDriver($this->dsn['phptype'], $this->dbDriver);
     }
     $con = Creole::getConnection($this->dsn);
     $this->log("DB connection established");
     return $con;
 }
 /**
  * Connect to the database.
  *
  * @throws     <b>AgaviDatabaseException</b> If a connection could not be 
  *                                           created.
  *
  * @author     Sean Kerr <*****@*****.**>
  * @author     David Zülke <*****@*****.**>
  * @since      0.9.0
  */
 protected function connect()
 {
     try {
         // determine how to get our settings
         $method = $this->getParameter('method', 'normal');
         switch ($method) {
             case 'normal':
                 // get parameters normally
                 // all params, because we can't know all names!
                 $dsn = $this->getParameters();
                 // remove our own
                 unset($dsn['method']);
                 unset($dsn['classpath']);
                 unset($dsn['compat_assoc_lower']);
                 unset($dsn['compat_rtrim_string']);
                 unset($dsn['persistent']);
                 break;
             case 'dsn':
                 $dsn = $this->getParameter('dsn');
                 if ($dsn == null) {
                     // missing required dsn parameter
                     $error = 'Database configuration specifies method "dsn", but is missing dsn parameter';
                     throw new AgaviDatabaseException($error);
                 }
                 break;
             case 'server':
                 // construct a DSN connection string from existing $_SERVER
                 // values
                 $dsn = $this->loadDSN($_SERVER);
                 break;
             case 'env':
                 // construct a DSN connection string from existing $_ENV
                 // values
                 $dsn = $this->loadDSN($_ENV);
                 break;
             default:
                 // who knows what the user wants...
                 $error = 'Invalid CreoleDatabase parameter retrieval method "%s"';
                 $error = sprintf($error, $method);
                 throw new AgaviDatabaseException($error);
         }
         // get creole class path
         $classPath = $this->getParameter('classpath');
         // include the creole file
         if ($classPath == null) {
             require_once 'creole/Creole.php';
         } else {
             require_once $classPath;
         }
         // set our flags
         $compatAssocLower = $this->getParameter('compat_assoc_lower', false);
         $compatRtrimString = $this->getParameter('compat_rtrim_string', false);
         $persistent = $this->getParameter('persistent', false);
         $flags = 0;
         $flags |= $compatAssocLower ? Creole::COMPAT_ASSOC_LOWER : 0;
         $flags |= $compatRtrimString ? Creole::COMPAT_RTRIM_STRING : 0;
         $flags |= $persistent ? Creole::PERSISTENT : 0;
         // do the duuuurtay work, right thurr
         if ($flags > 0) {
             $this->connection = Creole::getConnection($dsn, $flags);
         } else {
             $this->connection = Creole::getConnection($dsn);
         }
         // get our resource
         $this->resource = $this->connection->getResource();
         foreach ((array) $this->getParameter('init_queries') as $query) {
             $this->connection->executeUpdate($query);
         }
     } catch (SQLException $e) {
         // the connection's foobar'd
         throw new AgaviDatabaseException($e->toString());
     }
 }
Esempio n. 7
0
 /**
  *
  * @param      string $name The database name.
  * @return     Connection A database connection
  * @throws     PropelException - if no conneciton params, or SQLException caught when trying to connect.
  */
 public static function getConnection($name = null)
 {
     if ($name === null || $name != self::$configuration['datasources']['default']) {
         $name = self::getDefaultDB();
     }
     $con = isset(self::$connectionMap[$name]) ? self::$connectionMap[$name] : null;
     if ($con === null) {
         $dsn = isset(self::$configuration['datasources'][$name]['connection']) ? self::$configuration['datasources'][$name]['connection'] : null;
         if ($dsn === null) {
             throw new PropelException("No connection params set for " . $name);
         }
         include_once 'creole/Creole.php';
         // if specified, use custom driver
         if (isset(self::$configuration['datasources'][$name]['driver'])) {
             Creole::registerDriver($dsn['phptype'], self::$configuration['datasources'][$name]['driver']);
         }
         try {
             $con =& Creole::getConnection($dsn);
         } catch (SQLException $e) {
             throw new PropelException($e);
         }
         self::$connectionMap[$name] = $con;
     }
     return $con;
 }
Esempio n. 8
0
 /**
  * Close the Database Connection
  */
 public static function close_connection()
 {
     ActiveRecord::$conn = Creole::getConnection(ActiveRecord::parse_dsn())->close();
 }
 /**
  * Creates a new Connection as using the driver, url, userid and password specified.
  * The calling method is responsible for closing the connection.
  * @return Connection the newly created connection.
  * @throws BuildException if the UserId/Password/Url is not set or there is no suitable driver or the driver fails to load.
  */
 protected function getConnection()
 {
     if ($this->url === null) {
         throw new BuildException("Url attribute must be set!", $this->location);
     }
     try {
         $this->log("Connecting to " . $this->getUrl(), PROJECT_MSG_VERBOSE);
         $info = new Properties();
         $dsn = Creole::parseDSN($this->url);
         if (!isset($dsn["username"]) && $this->userId === null) {
             throw new BuildException("Username must be in URL or userid attribute must be set.", $this->location);
         }
         if ($this->userId) {
             $dsn["username"] = $this->getUserId();
         }
         if ($this->password) {
             $dsn["password"] = $this->getPassword();
         }
         if ($this->driver) {
             Creole::registerDriver($dsn['phptype'], $this->driver);
         }
         $conn = Creole::getConnection($dsn);
         $conn->setAutoCommit($this->autocommit);
         return $conn;
     } catch (SQLException $e) {
         throw new BuildException($e->getMessage(), $this->location);
     }
 }
 /**
  *  DBに接続する
  *
  *  @access public
  *  @return mixed   0:正常終了 Ethna_Error:エラー
  */
 function connect()
 {
     $this->db = Creole::getConnection($this->dsn);
     return 0;
 }
 /**
  * Connect to the database.
  *
  * @throws <b>sfDatabaseException</b> If a connection could not be created.
  */
 public function connect()
 {
     try {
         // determine how to get our settings
         $method = $this->getParameter('method', 'normal');
         switch ($method) {
             case 'normal':
                 // get parameters normally, and all are required
                 $database = $this->getParameter('database', null);
                 $hostspec = $this->getParameter('hostspec') ? $this->getParameter('hostspec') : ($this->getParameter('host') ? $this->getParameter('hostspec') : null);
                 $password = $this->getParameter('password', null);
                 $phptype = $this->getParameter('phptype', null);
                 $username = $this->getParameter('username', null);
                 $port = $this->getParameter('port', null);
                 $encoding = $this->getParameter('encoding', null);
                 $dsn = array('database' => $database, 'hostspec' => $hostspec, 'password' => $password, 'phptype' => $phptype, 'username' => $username, 'port' => $port, 'encoding' => $encoding);
                 break;
             case 'dsn':
                 $dsn = $this->getParameter('dsn');
                 if ($dsn == null) {
                     // missing required dsn parameter
                     $error = 'Database configuration specifies method "dsn", but is missing dsn parameter';
                     throw new sfDatabaseException($error);
                 }
                 break;
             case 'server':
                 // construct a DSN connection string from existing $_SERVER values
                 $dsn =& $this->loadDSN($_SERVER);
                 break;
             case 'env':
                 // construct a DSN connection string from existing $_ENV values
                 $dsn =& $this->loadDSN($_ENV);
                 break;
             default:
                 // who knows what the user wants...
                 $error = 'Invalid CreoleDatabase parameter retrieval method "%s"';
                 $error = sprintf($error, $method);
                 throw new sfDatabaseException($error);
         }
         // get creole class path
         $classPath = $this->getParameter('classpath');
         // include the creole file
         if ($classPath == null) {
             require_once 'creole/Creole.php';
         } else {
             require_once $classPath;
         }
         // set our flags
         $noAssocLower = $this->getParameter('no_assoc_lower', false);
         $persistent = $this->getParameter('persistent', false);
         $compatAssocLower = $this->getParameter('compat_assoc_lower', false);
         $compatRtrimString = $this->getParameter('compat_rtrim_string', false);
         $flags = 0;
         $flags |= $noAssocLower ? Creole::NO_ASSOC_LOWER : 0;
         $flags |= $persistent ? Creole::PERSISTENT : 0;
         $flags |= $compatAssocLower ? Creole::COMPAT_ASSOC_LOWER : 0;
         $flags |= $compatRtrimString ? Creole::COMPAT_RTRIM_STRING : 0;
         // do the duuuurtay work, right thurr
         if ($flags > 0) {
             $this->connection = Creole::getConnection($dsn, $flags);
         } else {
             $this->connection = Creole::getConnection($dsn);
         }
         // get our resource
         $this->resource = $this->connection->getResource();
     } catch (SQLException $e) {
         // the connection's foobar'd
         throw new sfDatabaseException($e->toString());
     }
 }
Esempio n. 12
0
    private function generate($name, $dsn)
    {
        $datasource = $name;
        $outputdir = dirname(__FILE__) . "/../../../components/entity";
        /*
         * start.
         */
        $conn = Creole::getConnection($dsn);
        $dbinfo = $conn->getDatabaseInfo();
        $base_dir = $outputdir . '/' . 'base';
        if (!file_exists($base_dir) && !mkdir($base_dir)) {
            print "could not make directory for base: {$outputdir}";
            exit;
        }
        foreach ($dbinfo->getTables() as $tbl) {
            $classname = "";
            $tablename = "";
            $capName = "";
            $pkdef = "";
            $coldef = "";
            $joindef = "";
            $aliasesdef = "";
            $tablename = strtolower($tbl->getName());
            $capName = $this->camelize($tablename);
            $classname = "Entity_{$capName}";
            $baseclassname = "Entity_Base_{$capName}";
            // columns
            $cols = array();
            foreach ($tbl->getColumns() as $col) {
                $cols[] = strtolower($col->getName());
            }
            // primary key
            $auto = 'FALSE';
            $pks = array();
            $pk = $tbl->getPrimaryKey();
            if (is_object($pk)) {
                foreach ($pk->getColumns() as $pkcol) {
                    $pks[] = strtolower($pkcol->getName());
                    if ($pkcol->isAutoIncrement()) {
                        $auto = 'TRUE';
                    }
                }
            }
            // join
            $aliases = array();
            $joindef_buf = array();
            $fks = $tbl->getForeignKeys();
            if (is_array($fks)) {
                foreach ($fks as $fk) {
                    $alias = "";
                    $entity = "";
                    $refdef = array();
                    $refs = $fk->getReferences();
                    if (is_array($refs)) {
                        //$alias = strtolower($fk->getName());
                        $alias = strtolower($refs[0][1]->getTable()->getName());
                        $entity = 'Entity_' . $this->camelize($refs[0][1]->getTable()->getName());
                        $aliases[] = array('name' => $alias, 'entity' => $entity);
                        foreach ($refs as $ref) {
                            $p = strtolower($ref[0]->getName());
                            $c = strtolower($ref[1]->getName());
                            $refdef[] = "                '{$p}' => '{$c}'";
                        }
                        $buf = "";
                        $buf .= "        '{$alias}' => array(\n";
                        $buf .= "            'entity' => '{$entity}',\n";
                        $buf .= "            'type' => 'INNER JOIN',\n";
                        $buf .= "            'relation' => array(\n";
                        $buf .= implode(",\n", $refdef);
                        $buf .= "\n";
                        $buf .= "            )\n";
                        $buf .= "        )";
                        $joindef_buf[] = $buf;
                    }
                }
            }
            if (count($joindef_buf)) {
                $joindef = implode(",\n", $joindef_buf);
            }
            if (count($aliases)) {
                foreach ($aliases as $alias) {
                    $aliasesdef .= <<<EOT
    /**
     * @var {$alias['entity']} 
     */
    public \${$alias['name']};


EOT;
                }
            }
            //$cols = array_diff($cols, $pks);
            foreach ($cols as $col) {
                $coldef .= "    public \$" . $col . ";\n";
            }
            //$coldef = "'". implode("',\n        '", $cols) ."'";
            $pkdef = "'" . implode("',\n'", $pks) . "'";
            // ベースクラスの作成
            $filepath = $outputdir . "/base/{$capName}.php";
            if (file_exists($filepath) && !$this->forceUpdate) {
                print "{$tablename}: base class already exists. \n";
                continue;
            }
            if (!($handle = fopen($filepath, 'wb'))) {
                print "{$filepath}: could not open file. \n";
                continue;
            }
            $contents = <<<EOT
class {$baseclassname} extends Teeple_ActiveRecord
{

    /**
     * 使用するデータソース名を指定します。
     * 指定が無い場合は、DEFAULT_DATASOURCE で設定されているDataSource名が使用されます。
     *
     * @var string
     */
    public static \$_DATASOURCE = '{$datasource}';
    
    /**
     * このエンティティのテーブル名を設定します。
     * 
     * <pre>
     * スキーマを設定する場合は、"スキーマ.テーブル名"とします。
     * 子クラスにて必ずセットする必要があります。
     * </pre>
     *
     * @var string
     */
    public static \$_TABLENAME = '{$tablename}';
    
    /**
     * プライマリキー列を設定します。
     * 
     * <pre>
     * プライマリキーとなるカラム名を配列で指定します。
     * 子クラスにて必ずセットする必要があります。
     * </pre>
     * 
     * @var array 
     */
    public static \$_PK = array(
        {$pkdef}
    );
    
    /**
     * このテーブルのカラム名をpublicプロパティとして設定します。(プライマリキーを除く)
     * <pre>
     * 子クラスにて必ずセットする必要があります。
     * </pre>
     */
{$coldef}
    
    /**
     * プライマリキーが自動セット(auto increment)かどうかを設定します。
     * 
     * <pre>
     * 子クラスにて必ずセットする必要があります。
     * </pre>
     * 
     * @var bool 
     */
    public static \$_AUTO = {$auto};

}
EOT;
            $contents = "<?php \n\n" . $contents . "\n\n?>";
            if (fwrite($handle, $contents) === FALSE) {
                print "{$filepath}: failed to write to the file. \n";
                continue;
            }
            print "{$tablename}: entity base class created . \n";
            fclose($handle);
            // エンティティクラスの作成
            $filepath = $outputdir . "/{$capName}.php";
            if (file_exists($filepath)) {
                print "{$tablename}: entity class already exists. \n";
                continue;
            }
            if (!($handle = fopen($filepath, 'wb'))) {
                print "{$filepath}: could not open file. \n";
                continue;
            }
            $contents = <<<EOT
/**
 * Entity Class for {$tablename}
 *
 * エンティティに関するロジック等はここに実装します。
 * @package entity
 */
class {$classname} extends {$baseclassname}
{
    /**
     * インスタンスを取得します。
     * @return {$classname}
     */
    public static function get() {
        return Teeple_Container::getInstance()->getEntity('{$classname}');
    }
    
    /**
     * 単一行の検索を実行します。
     * @param \$id
     * @return {$classname}
     */
    public function find(\$id=null) {
        return parent::find(\$id);
    }
    
    /**
     * JOINするテーブルを設定します。
     * ※generatorが吐き出した雛形を修正してください。
     * 
     * ここに設定してある定義は、\$this->join('aliasname') で利用できる。<br/>
     * ※ここに設定しただけではJOINされない。
     * 
     * <pre>
     * 指定方法: 'アクセスするための別名' => 設定値の配列
     * 設定値の配列:
     *   'entity' => エンティティのクラス名
     *  'columns' => 取得するカラム文字列(SQLにセットするのと同じ形式)
     *   'type' => JOINのタイプ(SQLに書く形式と同じ)(省略した場合はINNER JOIN)
     *   'relation' => JOINするためのリレーション設定
     *      「本クラスのキー名 => 対象クラスのキー名」となります。
     *   'condition' => JOINするための設定だがリテラルで指定するもの
     * 
     * 値の例:
     * 
     * \$join_config = array(
     *     'aliasname' => array(
     *         'entity' => 'Entity_Fuga',
     *         'columns' => 'foo, bar, hoge',
     *         'type' => 'LEFT JOIN',
     *         'relation' => array(
     *             'foo_id' => 'bar_id'
     *         ),
     *         'condition' => 'aliasname.status = 1 AND parent.status = 1'
     *     )
     * );
     * </pre>
     * 
     * @var array
     */
    public static \$_JOINCONFIG = array(
{$joindef}
    );
    
{$aliasesdef}

}
EOT;
            $contents = "<?php \n\n" . $contents . "\n\n?>";
            if (fwrite($handle, $contents) === FALSE) {
                print "{$filepath}: failed to write to the file. \n";
                continue;
            }
            print "{$tablename}: entity class created . \n";
            fclose($handle);
        }
        // end of foreach
    }
Esempio n. 13
0
 public function __construct($dsn, $path = null)
 {
     $this->db = Creole::getConnection($dsn);
     $this->path = $path;
 }
Esempio n. 14
0
 /**
  * Test to make sure that a de-registered driver cannot
  * be used.
  */
 public function testUnregisterDriver()
 {
     Creole::deregisterDriver('mysql');
     try {
         $driver = Creole::getConnection('mysql://hostname/dbname');
         $this->fail("Expected SQLException to be thrown by attempt to connect to unregistered driver type.");
     } catch (SQLException $e) {
         $this->expectException("No driver has been registered to handle connection type: mysql", $e);
     }
     // now put it back :)
     Creole::registerDriver('mysql', 'creole.drivers.mysql.MySQLConnection');
 }
 /**
  * Take the base url, the target database and insert a set of SQL
  * files into the target database.
  *
  * @param      string $url
  * @param      string $database
  * @param      array $transactions
  */
 private function insertDatabaseSqlFiles($url, $database, $transactions)
 {
     $url = str_replace("@DB@", $database, $url);
     $this->log("Our new url -> " . $url);
     try {
         $buf = "Database settings:\n" . " driver: " . ($this->driver ? $this->driver : "(default)") . "\n" . " URL: " . $url . "\n" . ($this->userId ? " user: "******"\n" : "") . ($this->password ? " password: "******"\n" : "");
         $this->log($buf, PROJECT_MSG_VERBOSE);
         $dsn = Creole::parseDSN($url);
         if ($this->userId) {
             $dsn["username"] = $this->userId;
         }
         if ($this->password) {
             $dsn["password"] = $this->password;
         }
         if ($this->driver) {
             Creole::registerDriver($dsn['phptype'], $this->driver);
         }
         $this->conn = Creole::getConnection($dsn);
         $this->conn->setAutoCommit($this->autocommit);
         $this->statement = $this->conn->createStatement();
         $out = null;
         try {
             if ($this->output !== null) {
                 $this->log("Opening PrintStream to output file " . $this->output->__toString(), PROJECT_MSG_VERBOSE);
                 $out = new FileWriter($this->output);
             }
             // Process all transactions
             for ($i = 0, $size = count($transactions); $i < $size; $i++) {
                 $transactions[$i]->runTransaction($out);
                 if (!$this->autocommit) {
                     $this->log("Commiting transaction", PROJECT_MSG_VERBOSE);
                     $this->conn->commit();
                 }
             }
         } catch (Exception $e) {
             if ($out) {
                 $out->close();
             }
         }
     } catch (IOException $e) {
         if (!$this->autocommit && $this->conn !== null && $this->onError == "abort") {
             try {
                 $this->conn->rollback();
             } catch (SQLException $ex) {
                 // do nothing.
                 System::println("Rollback failed.");
             }
         }
         if ($this->statement) {
             $this->statement->close();
         }
         throw new BuildException($e);
     } catch (SQLException $e) {
         if (!$this->autocommit && $this->conn !== null && $this->onError == "abort") {
             try {
                 $this->conn->rollback();
             } catch (SQLException $ex) {
                 // do nothing.
                 System::println("Rollback failed");
             }
         }
         if ($this->statement) {
             $this->statement->close();
         }
         throw new BuildException($e);
     }
     $this->statement->close();
     $this->log($this->goodSql . " of " . $this->totalSql . " SQL statements executed successfully");
 }
Esempio n. 16
0
 /**
  * Return a database connection object
  *
  * @return Creole db object
  */
 public static function getDBConnection()
 {
     if (!self::$dbConnection) {
         include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . "creole" . DIRECTORY_SEPARATOR . "Creole.php";
         self::getLogger()->logQuery("Creating a database connection");
         self::$dbConnection = Creole::getConnection(self::$dsn);
         self::getLogger()->logQueryExecutionTime();
         self::$dbConnection->executeUpdate("SET NAMES 'utf8'");
         self::$dbConnection->executeUpdate("SET @@session.sql_mode=''");
     }
     return self::$dbConnection;
 }
Esempio n. 17
0
 /**
  * Iterates through each datamodel/database, dumps the contents of all tables and creates a DOM XML doc.
  *
  * @return void
  * @throws BuildException
  */
 public function main()
 {
     $this->validate();
     $buf = "Database settings:\n" . " driver: " . ($this->databaseDriver ? $this->databaseDriver : "(default)") . "\n" . " URL: " . $this->databaseUrl . "\n" . ($this->databaseUser ? " user: "******"\n" : "") . ($this->databasePassword ? " password: "******"\n" : "");
     // deprecated
     $this->log($buf, PROJECT_MSG_VERBOSE);
     // 1) First create the Data XML -> database name map.
     $this->createDataDbMap();
     // 2) Now go create the XML files from teh database(s)
     foreach ($this->getDataModels() as $dataModel) {
         // there is really one 1 db per datamodel
         foreach ($dataModel->getDatabases() as $database) {
             // if database name is specified, then we only want to dump that one db.
             if (empty($this->databaseName) || $this->databaseName && $database->getName() == $this->databaseName) {
                 $outFile = $this->getMappedFile($dataModel->getName());
                 $this->log("Dumping data to XML for database: " . $database->getName());
                 $this->log("Writing to XML file: " . $outFile->getName());
                 try {
                     $url = str_replace("@DB@", $database->getName(), $this->databaseUrl);
                     $buf = "Database settings:\n" . " driver: " . ($this->databaseDriver ? $this->databaseDriver : "(default)") . "\n" . " URL: " . $url . "\n" . ($this->databaseUser ? " user: "******"\n" : "") . ($this->databasePassword ? " password: "******"\n" : "");
                     $this->log($buf, PROJECT_MSG_VERBOSE);
                     $dsn = Creole::parseDSN($url);
                     // deprecated, but here for BC
                     if ($this->databaseUser) {
                         $dsn['username'] = $this->databaseUser;
                     }
                     if ($this->databasePassword) {
                         $dsn['password'] = $this->databasePassword;
                     }
                     if ($this->databaseName) {
                         $dsn['database'] = $this->databaseName;
                     }
                     if ($this->databaseDriver) {
                         Creole::registerDriver($dsn['phptype'], $this->databaseDriver);
                     }
                     $this->conn = Creole::getConnection($dsn);
                     $doc = $this->createXMLDoc($database);
                     $doc->save($outFile->getAbsolutePath());
                 } catch (SQLException $se) {
                     $this->log("SQLException while connecting to DB: " . $se->getMessage(), PROJECT_MSG_ERR);
                     throw new BuildException($se);
                 }
             }
             // if databaseName && database->getName == databaseName
         }
         // foreach database
     }
     // foreach datamodel
 }
 /**
  * Test an ASSOC fetch with a connection that has the Creole::NO_ASSOC_LOWER flag set.
  */
 public function testFetchmodeAssocNoChange()
 {
     $exch = DriverTestManager::getExchange('ResultSetTest.ALL_RECORDS');
     $conn2 = Creole::getConnection(DriverTestManager::getDSN(), Creole::NO_ASSOC_LOWER);
     DriverTestManager::initDb($conn2);
     $rs = $conn2->executeQuery($exch->getSql(), ResultSet::FETCHMODE_ASSOC);
     $rs->next();
     $keys = array_keys($rs->getRow());
     $this->assertEquals("ProductID", $keys[0], 0, "Expected to find mixed-case column name.");
     $rs->close();
     // do NOT close the connection; in many cases both COnnection objects will share
     // the same db connection
 }
Esempio n. 19
0
 /**
  *
  * @param      string $name The database name.
  * @return     Connection A database connection
  * @throws     PropelException - if no conneciton params, or SQLException caught when trying to connect.
  */
 public static function getConnection($name = null)
 {
     if ($name === null) {
         $name = self::getDefaultDB();
     }
     $con = isset(self::$connectionMap[$name]) ? self::$connectionMap[$name] : null;
     if ($con === null || $name === 'dbarray') {
         $dsn = isset(self::$configuration['datasources'][$name]['connection']) ? self::$configuration['datasources'][$name]['connection'] : null;
         if ($dsn === null) {
             if (isset($_SESSION['PROCESS'])) {
                 /** Added By Erik Amaru <erik@colosa.com *******************************
                  * @date: 27-05-08 11:48                                                *
                  * @Description: this was added for the additional database connections *
                  ***********************************************************************/
                 G::LoadClass('dbConnections');
                 $oDbConnections = new dbConnections($_SESSION['PROCESS']);
                 $oDbConnections->loadAdditionalConnections();
                 $dsn = isset(self::$configuration['datasources'][$name]['connection']) ? self::$configuration['datasources'][$name]['connection'] : null;
             } else {
                 throw new PropelException("No connection params set for " . $name);
             }
         }
         include_once 'creole/Creole.php';
         // if specified, use custom driver
         if (isset(self::$configuration['datasources'][$name]['driver'])) {
             Creole::registerDriver($dsn['phptype'], self::$configuration['datasources'][$name]['driver']);
         }
         try {
             $con = Creole::getConnection($dsn);
         } catch (SQLException $e) {
             throw new PropelException($e);
         }
         self::$connectionMap[$name] = $con;
     }
     return $con;
 }
 /**
  * This function provides the connection to the database
  *
  * @access public
  * @return String contains information from the connection to the database
  */
 public function getConnection()
 {
     try {
         /* try to connect to database */
         $dsn = $this->DATA->configuration['sqlconnection'];
         $conntype = $this->DATA->configuration['sqlconnection']['conntype'];
         $conn = Creole::getConnection($dsn, $conntype);
         /* return connection */
         return $conn;
     } catch (Exception $ex) {
         /* handle exception and terminate script */
         phpmediadb_exception::handleException($ex);
     }
 }
Esempio n. 21
0
<?php

require_once 'creole/Creole.php';
/* fix $dsn, $datasource, $outputdir to suit your environment */
$dsn = array('phptype' => 'mysql', 'hostspec' => 'localhost', 'username' => 'default', 'password' => 'default', 'database' => 'default');
$datasource = "default";
$outputdir = dirname(__FILE__) . "/../../../../components/entity";
/*
 * start. 
 */
$conn = Creole::getConnection($dsn);
$dbinfo = $conn->getDatabaseInfo();
$base_dir = $outputdir . '/' . 'base';
if (!file_exists($base_dir) && !mkdir($base_dir)) {
    print "could not make directory for base: {$outputdir}";
    exit;
}
foreach ($dbinfo->getTables() as $tbl) {
    $classname = "";
    $tablename = "";
    $capName = "";
    $pkdef = "";
    $coldef = "";
    $joindef = "";
    $aliasesdef = "";
    $tablename = strtolower($tbl->getName());
    $ar = split('_', $tablename);
    foreach ($ar as $key => $val) {
        $ar[$key] = ucfirst($val);
    }
    $capName = join('', $ar);
 public static function connect()
 {
     self::$conn = Creole::getConnection(self::$dsn);
 }