public static function getFactory() { if (!self::$factory) { self::$factory = new Database(); } return self::$factory; }
/** * 数据库 *+------ */ public function action_database() { $db = Database::factory('backup'); var_dump($db->select("select * from test")->fetchAll()); var_dump($db->select("select * from test")->fetchRow()); var_dump($db->select("select * from test")->fetchOne()); }
/** * Delete a subscription. */ public function delete($topic, $subscriber) { $sql = "DELETE FROM subscriptions WHERE topic = '{$topic}' AND subscriber = '{$subscriber}'"; $db = Database::factory(); $db->query($sql); echo "Delete Subscription"; // db_query("DELETE FROM {push_hub_subscriptions} WHERE topic = '%s' AND subscriber = '%s'", $topic, $subscriber); }
function gc($max_life_time) { if ($max_life_time == 0) { return TRUE; } $exp_time = Date::time() - $max_life_time; $db = Database::factory($this->db_name); $ret = $db->query('DELETE FROM `_session` WHERE mtime < %d', $exp_time); return !is_null($ret); }
function __construct($name, $SQL, $count_SQL = NULL, $db = NULL) { $this->name = $name; $this->SQL = $SQL; $this->db = $db instanceof Database ? $db : Database::factory($db); if (!$count_SQL) { $count_SQL = preg_replace('/\\bSQL_CALC_FOUND_ROWS\\b/', '', $SQL); $count_SQL = preg_replace('/^(SELECT)\\s(.+?)\\s(FROM)\\s/', '$1 COUNT($2) count $3', $count_SQL); $count_SQL = preg_replace('/ COUNT\\((.+?)\\.\\*\\) count/', ' COUNT($1.id) count', $count_SQL); $count_SQL = preg_replace('/\\sORDER BY.+$/', '', $count_SQL); $count_SQL = preg_replace('/\\sLIMIT.+$/', '', $count_SQL); } $this->count_SQL = $count_SQL; $this->check_query(); }
/** * 初始化 * * @param string $db 数据库名称 * */ public function minit($db = '') { // 表前缀 $this->dbname = 'database'; if (!empty($db)) { $this->dbname = $db; } if (empty($this->tablePrefixArray[$this->dbname])) { $configs = Wave::app()->config[$this->dbname]; $this->tablePrefixArray[$this->dbname] = $configs['master']['table_prefix']; } if (empty($this->dbArray[$this->dbname])) { $this->dbArray[$this->dbname] = Database::factory($this->dbname); } $this->init(); }
function __construct($selector, $db = NULL) { $this->db = $db instanceof Database ? $db : Database::factory($db); if ($selector instanceof ORM_Model) { $this->objects = array($selector->id => $selector); $this->count = $this->length = 1; $this->name = $selector->name(); $this->selector = $this->name . '#' . $selector->id; $this->current_id = $selector->id; //不需要再查询 $this->set_query('*', TRUE); } elseif (preg_match(Q_Query::PATTERN_EMPTY, $selector, $parts)) { $this->objects = array(); $this->current_id = 0; $this->count = $this->length = 0; $this->name = $parts[1]; $this->selector = $selector; //不需要再查询 $this->set_query('*', TRUE); } else { $this->selector = $selector; } }
/** * Really opens a connection. Uncached. * Returns a Database object whether or not the connection was successful. * @access private * * @param array $server * @param string|bool $dbNameOverride Use "" to not select any database * @return Database * @throws DBAccessError * @throws InvalidArgumentException */ protected function reallyOpenConnection(array $server, $dbNameOverride = false) { if ($this->disabled) { throw new DBAccessError(); } if ($dbNameOverride !== false) { $server['dbname'] = $dbNameOverride; } // Let the handle know what the cluster master is (e.g. "db1052") $masterName = $this->getServerName($this->getWriterIndex()); $server['clusterMasterHost'] = $masterName; // Log when many connection are made on requests if (++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD) { $this->perfLogger->warning(__METHOD__ . ": " . "{$this->connsOpened}+ connections made (master={$masterName})"); } $server['srvCache'] = $this->srvCache; // Set loggers and profilers $server['connLogger'] = $this->connLogger; $server['queryLogger'] = $this->queryLogger; $server['errorLogger'] = $this->errorLogger; $server['profiler'] = $this->profiler; $server['trxProfiler'] = $this->trxProfiler; // Use the same agent and PHP mode for all DB handles $server['cliMode'] = $this->cliMode; $server['agent'] = $this->agent; // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the // application calls LoadBalancer::commitMasterChanges() before the PHP script completes. $server['flags'] = isset($server['flags']) ? $server['flags'] : IDatabase::DBO_DEFAULT; // Create a live connection object try { $db = Database::factory($server['type'], $server); } catch (DBConnectionError $e) { // FIXME: This is probably the ugliest thing I have ever done to // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS $db = $e->db; } $db->setLBInfo($server); $db->setLazyMasterHandle($this->getLazyConnectionRef(self::DB_MASTER, [], $db->getDomainID())); $db->setTableAliases($this->tableAliases); if ($server['serverIndex'] === $this->getWriterIndex()) { if ($this->trxRoundId !== false) { $this->applyTransactionRoundFlags($db); } foreach ($this->trxRecurringCallbacks as $name => $callback) { $db->setTransactionListener($name, $callback); } } return $db; }
/** * @param string $filename * @param array $p Options map; supports: * - flags : (same as __construct counterpart) * - trxMode : (same as __construct counterpart) * - dbDirectory : (same as __construct counterpart) * @return DatabaseSqlite * @since 1.25 */ public static function newStandaloneInstance($filename, array $p = []) { $p['dbFilePath'] = $filename; $p['schema'] = false; $p['tablePrefix'] = ''; return Database::factory('sqlite', $p); }
/** * Get (or reuse) a connection to a lock DB * * @param string $lockDb * @return IDatabase * @throws DBError * @throws UnexpectedValueException */ protected function getConnection($lockDb) { if (!isset($this->conns[$lockDb])) { if ($this->dbServers[$lockDb] instanceof IDatabase) { // Direct injected connection hande for $lockDB $db = $this->dbServers[$lockDb]; } elseif (is_array($this->dbServers[$lockDb])) { // Parameters to construct a new database connection $config = $this->dbServers[$lockDb]; $db = Database::factory($config['type'], $config); } else { throw new UnexpectedValueException("No server called '{$lockDb}'."); } $db->clearFlag(DBO_TRX); # If the connection drops, try to avoid letting the DB rollback # and release the locks before the file operations are finished. # This won't handle the case of DB server restarts however. $options = []; if ($this->lockExpiry > 0) { $options['connTimeout'] = $this->lockExpiry; } $db->setSessionOptions($options); $this->initConnection($lockDb, $db); $this->conns[$lockDb] = $db; } return $this->conns[$lockDb]; }
/** * Get the primary database (part of the finalize process) */ protected function finalDatabasePrimary() : Database { $databases = \Airship\loadJSON(ROOT . '/config/databases.json'); $dbConf = $databases['default'][0]; $conf = [isset($dbConf['dsn']) ? $dbConf['dsn'] : $dbConf]; if (isset($dbConf['username']) && isset($dbConf['password'])) { $conf[] = $dbConf['username']; $conf[] = $dbConf['password']; if (isset($dbConf['options'])) { $conf[] = $dbConf['options']; } } elseif (isset($dbConf['options'])) { $conf[1] = ''; $conf[2] = ''; $conf[3] = $dbConf['options']; } if (empty($conf)) { die; } return Database::factory(...$conf); }
static function db($name) { $db = Database::factory(); return $db; }
/** * @return Status */ public function setupDatabase() { $dir = $this->getVar('wgSQLiteDataDir'); # Sanity check. We checked this before but maybe someone deleted the # data dir between then and now $dir_status = self::dataDirOKmaybeCreate($dir, false); if (!$dir_status->isOK()) { return $dir_status; } $db = $this->getVar('wgDBname'); # Make the main and cache stub DB files $status = Status::newGood(); $status->merge($this->makeStubDBFile($dir, $db)); $status->merge($this->makeStubDBFile($dir, "wikicache")); if (!$status->isOK()) { return $status; } # Nuke the unused settings for clarity $this->setVar('wgDBserver', ''); $this->setVar('wgDBuser', ''); $this->setVar('wgDBpassword', ''); $this->setupSchemaVars(); # Create the global cache DB try { $conn = Database::factory('sqlite', ['dbname' => 'wikicache', 'dbDirectory' => $dir]); # @todo: don't duplicate objectcache definition, though it's very simple $sql = <<<EOT \tCREATE TABLE IF NOT EXISTS objectcache ( \t keyname BLOB NOT NULL default '' PRIMARY KEY, \t value BLOB, \t exptime TEXT \t) EOT; $conn->query($sql); $conn->query("CREATE INDEX IF NOT EXISTS exptime ON objectcache (exptime)"); $conn->query("PRAGMA journal_mode=WAL"); // this is permanent $conn->close(); } catch (DBConnectionError $e) { return Status::newFatal('config-sqlite-connection-error', $e->getMessage()); } # Open the main DB return $this->getConnection(); }
/** * Get a database class * * @static array $_cache * * @param string $id Database identifier * @return Database * * @throws DBException */ function get_database(string $id = 'default') : Database { static $_cache = []; if (isset($_cache[$id])) { return $_cache[$id]; } $state = State::instance(); if (isset($state->database_connections[$id])) { if (\count($state->database_connections[$id]) === 1) { $k = \array_keys($state->database_connections[$id])[0]; } elseif (\count($state->database_connections[$id]) > 0) { $r = \random_int(0, \count($state->database_connections[$id]) - 1); $k = \array_keys($state->database_connections[$id])[$r]; } else { throw new DBException(\trk('errors.database.not_found', $id)); } $_cache[$id] = Database::factory(...$state->database_connections[$id][$k]); return $_cache[$id]; } throw new DBException(\trk('errors.database.not_found', $id)); }
/** * @return Status */ public function submitSettingsForm() { $this->setVarsFromRequest(['wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount', '_WebWindowsAuthentication']); if ($this->getVar('_SameAccount')) { $this->setVar('_WebWindowsAuthentication', $this->getVar('_InstallWindowsAuthentication')); $this->setVar('wgDBuser', $this->getVar('_InstallUser')); $this->setVar('wgDBpassword', $this->getVar('_InstallPassword')); } if ($this->getVar('_WebWindowsAuthentication') == 'windowsauth') { $this->setVar('wgDBuser', ''); $this->setVar('wgDBpassword', ''); $this->setVar('wgDBWindowsAuthentication', true); } else { $this->setVar('wgDBWindowsAuthentication', false); } if ($this->getVar('_CreateDBAccount') && $this->getVar('_WebWindowsAuthentication') == 'sqlauth' && strval($this->getVar('wgDBpassword')) == '') { return Status::newFatal('config-db-password-empty', $this->getVar('wgDBuser')); } // Validate the create checkbox $canCreate = $this->canCreateAccounts(); if (!$canCreate) { $this->setVar('_CreateDBAccount', false); $create = false; } else { $create = $this->getVar('_CreateDBAccount'); } if (!$create) { // Test the web account $user = $this->getVar('wgDBuser'); $password = $this->getVar('wgDBpassword'); if ($this->getVar('_WebWindowsAuthentication') == 'windowsauth') { $user = '******'; $password = '******'; } try { Database::factory('mssql', ['host' => $this->getVar('wgDBserver'), 'user' => $user, 'password' => $password, 'dbname' => false, 'flags' => 0, 'tablePrefix' => $this->getVar('wgDBprefix'), 'schema' => $this->getVar('wgDBmwschema')]); } catch (DBConnectionError $e) { return Status::newFatal('config-connection-error', $e->getMessage()); } } return Status::newGood(); }
function remove($token) { $db = Database::factory($this->db_name); return FALSE != $db->query('DELETE FROM `%s` WHERE `token`="%s"', $this->table, $token); }
/** * @return Closure */ protected function getDBFactory() { $type = $this->dbType; $params = ['host' => $this->dbServer, 'user' => $this->dbUser, 'password' => $this->dbPassword, 'dbname' => $this->dbName, 'flags' => $this->dbFlags, 'tablePrefix' => $this->tablePrefix, 'foreign' => true]; return function ($index) use($type, $params) { return Database::factory($type, $params); }; }
<label>Title:</label> <input type="text" name="title" /><br /> <label>Author:</label> <input type="text" name="author" /><br /> <label>Content:</label> <textarea name="content"></textarea><br /> <input type="submit" name="add" /> </form> <h1>Newest informations, you have <?php echo $count; ?> news</h1> <hr /> <?php $news = Database::factory('news')->select()->order_by('id', 'DESC')->find_all(); foreach ($news as $post) { ?> <h2><?php echo $post->title; ?> </h2> <small><?php echo $post->author; ?> </small> <p><?php echo $post->content; ?> </p>
/** * Open a PG connection with given parameters * @param string $user User name * @param string $password Password * @param string $dbName Database name * @param string $schema Database schema * @return Status */ protected function openConnectionWithParams($user, $password, $dbName, $schema) { $status = Status::newGood(); try { $db = Database::factory('postgres', array('host' => $this->getVar('wgDBserver'), 'user' => $user, 'password' => $password, 'dbname' => $dbName, 'schema' => $schema)); $status->value = $db; } catch (DBConnectionError $e) { $status->fatal('config-connection-error', $e->getMessage()); } return $status; }
/** * execute 执行操作 * @return mixed object */ public function execute($db = '') { //此处需要加载数据库配置信息 //$config = Config::load('database.'.$db); //连接数据库 $this->_databaseObject = Database::factory($config['type'])->host($config['connection']['hostname'])->port($config['connection']['port'])->user($config['connection']['username'])->password($config['connection']['password'])->dbName($config['connection']['database'])->charset($config['charset'])->connect(); $this->_databaseObject->query(self::$_sql); return $this; }
public static function newInstance(array $p = []) { $p['dbFilePath'] = ':memory:'; $p['schema'] = false; return Database::factory('SqliteMock', $p); }
/** * Get a connection to the specified database * * @param int $serverIndex * @return IDatabase * @throws MWException */ protected function getDB($serverIndex) { if (!isset($this->conns[$serverIndex])) { if ($serverIndex >= $this->numServers) { throw new MWException(__METHOD__ . ": Invalid server index \"{$serverIndex}\""); } # Don't keep timing out trying to connect for each call if the DB is down if (isset($this->connFailureErrors[$serverIndex]) && time() - $this->connFailureTimes[$serverIndex] < 60) { throw $this->connFailureErrors[$serverIndex]; } # If server connection info was given, use that if ($this->serverInfos) { $info = $this->serverInfos[$serverIndex]; $type = isset($info['type']) ? $info['type'] : 'mysql'; $host = isset($info['host']) ? $info['host'] : '[unknown]'; $this->logger->debug(__CLASS__ . ": connecting to {$host}"); // Use a blank trx profiler to ignore expections as this is a cache $info['trxProfiler'] = new TransactionProfiler(); $db = Database::factory($type, $info); $db->clearFlag(DBO_TRX); } else { $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER; if ($this->getSeparateMainLB()) { $db = $this->getSeparateMainLB()->getConnection($index); $db->clearFlag(DBO_TRX); // auto-commit mode } else { $db = wfGetDB($index); // Can't mess with transaction rounds (DBO_TRX) :( } } $this->logger->debug(sprintf("Connection %s will be used for SqlBagOStuff", $db)); $this->conns[$serverIndex] = $db; } return $this->conns[$serverIndex]; }
/** * @return Status */ public function setupUser() { $dbUser = $this->getVar('wgDBuser'); if ($dbUser == $this->getVar('_InstallUser')) { return Status::newGood(); } $status = $this->getConnection(); if (!$status->isOK()) { return $status; } $this->setupSchemaVars(); $dbName = $this->getVar('wgDBname'); $this->db->selectDB($dbName); $server = $this->getVar('wgDBserver'); $password = $this->getVar('wgDBpassword'); $grantableNames = []; if ($this->getVar('_CreateDBAccount')) { // Before we blindly try to create a user that already has access, try { // first attempt to connect to the database Database::factory('mysql', ['host' => $server, 'user' => $dbUser, 'password' => $password, 'dbname' => false, 'flags' => 0, 'tablePrefix' => $this->getVar('wgDBprefix')]); $grantableNames[] = $this->buildFullUserName($dbUser, $server); $tryToCreate = false; } catch (DBConnectionError $e) { $tryToCreate = true; } } else { $grantableNames[] = $this->buildFullUserName($dbUser, $server); $tryToCreate = false; } if ($tryToCreate) { $createHostList = [$server, 'localhost', 'localhost.localdomain', '%']; $createHostList = array_unique($createHostList); $escPass = $this->db->addQuotes($password); foreach ($createHostList as $host) { $fullName = $this->buildFullUserName($dbUser, $host); if (!$this->userDefinitelyExists($host, $dbUser)) { try { $this->db->begin(__METHOD__); $this->db->query("CREATE USER {$fullName} IDENTIFIED BY {$escPass}", __METHOD__); $this->db->commit(__METHOD__); $grantableNames[] = $fullName; } catch (DBQueryError $dqe) { if ($this->db->lastErrno() == 1396) { // User (probably) already exists $this->db->rollback(__METHOD__); $status->warning('config-install-user-alreadyexists', $dbUser); $grantableNames[] = $fullName; break; } else { // If we couldn't create for some bizzare reason and the // user probably doesn't exist, skip the grant $this->db->rollback(__METHOD__); $status->warning('config-install-user-create-failed', $dbUser, $dqe->getText()); } } } else { $status->warning('config-install-user-alreadyexists', $dbUser); $grantableNames[] = $fullName; break; } } } // Try to grant to all the users we know exist or we were able to create $dbAllTables = $this->db->addIdentifierQuotes($dbName) . '.*'; foreach ($grantableNames as $name) { try { $this->db->begin(__METHOD__); $this->db->query("GRANT ALL PRIVILEGES ON {$dbAllTables} TO {$name}", __METHOD__); $this->db->commit(__METHOD__); } catch (DBQueryError $dqe) { $this->db->rollback(__METHOD__); $status->fatal('config-install-user-grant-failed', $dbUser, $dqe->getText()); } } return $status; }
/** * Método do Active Record que deleta um objeto do banco de dados, porém o objeto não pode ser uma nova instância * @return void */ public function delete() { $class = get_called_class(); $db = Database::factory(); $db->{$class}->delete($this); $db->save(); }
public function openConnectionToAnyDB($user, $password) { $dbs = ['template1', 'postgres']; if (!in_array($this->getVar('wgDBname'), $dbs)) { array_unshift($dbs, $this->getVar('wgDBname')); } $conn = false; $status = Status::newGood(); foreach ($dbs as $db) { try { $p = ['host' => $this->getVar('wgDBserver'), 'user' => $user, 'password' => $password, 'dbname' => $db]; $conn = Database::factory('postgres', $p); } catch (DBConnectionError $error) { $conn = false; $status->fatal('config-pg-test-error', $db, $error->getMessage()); } if ($conn !== false) { break; } } if ($conn !== false) { return Status::newGood($conn); } else { return $status; } }
//Initialize the random number generator mt_srand(LOGD::make_seed()); //Initialize the Session and the Routing Session::get_session(); Routing::init(); //check if the dbconfig.default.php exist, if yes - we have to install the game if (!file_exists(dirname(LOGD_ROOT) . DIRECTORY_SEPARATOR . '.dbconfig' . EXT) && file_exists(dirname(LOGD_ROOT) . DIRECTORY_SEPARATOR . '.dbconfig.default' . EXT)) { //try-catch the installer, if it fails try { new \Install\Installer(); } catch (LOGD_Exception $e) { $e->print_error(); } exit(1); } //Initialize the language Class //todo this is later only a fallback if nothing found in the database //I18N::init(GAME_LANGUAGE); //including the .dbconfig.php with all Database-Constants include dirname(LOGD_ROOT) . DIRECTORY_SEPARATOR . '.dbconfig' . EXT; //Load the default template instance // @todo maybe set it later via database //Template::get_instance(null,false); //Set the page_header and page_footer every time // @todo set it later via database Replacer::page_header('LOGD - OOP'); $test = Database::factory(); //todo: implement routing //Routing::init()->get_view(); //Render the first view View::create('start')->render();