Ejemplo n.º 1
0
 /**
  * Example connection strings:
  * 
  * <pre class="highlighted"><code class="php">PicoraActiveRecord::connect('sqlite://relative_path_to_sqlite_database');
  * PicoraActiveRecord::connect('mysql://*****:*****@host/database_name');</code></pre>
  *
  * @param string $connection_string
  * @return bool
  */
 public static final function connect($connection_string, $username = false, $password = false, $driver_options = false)
 {
     if (preg_match('|sqlite\\://(.+)|', $connection_string)) {
         self::$__connection_type__ = 'sqlite';
         if (!preg_match('|sqlite\\://(.+)|', $connection_string, $match)) {
             throw new Exception('SQLite connection string should be in the following format: sqlite://path/to/file.db');
         }
         $file = $match[1];
         $error = '';
         if (!is_writable($file) || !is_readable($file)) {
             throw new Exception($file . " must be writable.");
         }
         if (!is_writable(dirname($file)) || !is_readable(dirname($file))) {
             throw new Exception(dirname($file) . "/ must be writable.");
         }
         self::$__connection__ = new SQLiteDatabase($file, 0666, $error);
         if (!self::$__connection__) {
             throw new Exception($error);
         }
         self::$__connection__->busyTimeout(30000);
         self::$__connection__->query('PRAGMA short_column_names = 1;');
         return true;
     } elseif (preg_match('|mysql\\://(.+)|', $connection_string)) {
         self::$__connection_type__ = 'mysql';
         if (!preg_match('|mysql\\://([^:]+):?([^@]*)@([^/]+)/(.+)|', $connection_string, $match)) {
             throw new Exception('MySql connection string should be in the following format: mysql://username:password@host/database_name');
         }
         self::$__connection__ = mysql_connect($match[3], $match[1], $match[2], true);
         if (!self::$__connection__) {
             throw new Exception('Could not connect to MySQL. Tried to connect to MySQL at ' . $match[3] . '. MySQL issued this error: "' . mysql_error() . '"');
         }
         if (!mysql_select_db($match[4], self::$__connection__)) {
             throw new Exception('Could not Select Database. Tried to select the database ' . $match[4] . '. MySQL issued this error: "' . mysql_error() . '"');
         }
         @mysql_query("SET NAMES 'utf8';", self::$__connection__);
         return true;
     } else {
         self::$__connection_type__ = 'pdo';
         self::$__connection__ = new PDO($connection_string, $username, $password, $driver_options);
         return true;
     }
 }