connect() public static method

Creates a new Connection object and connects it to specified database.
public static connect ( $config = [], $name ) : Dibi\Connection
return Dibi\Connection
Exemplo n.º 1
0
 /**
  * Spoji se z databzi.
  *
  * @return Bobr_Bobr
  * @throws DibiDriverException
  */
 private function connectToDatabase()
 {
     // @todo odchytavat vyjimku pri nepovedenem spojeni.
     $config = new Config();
     $connect = dibi::connect(array('driver' => 'postgre', 'string' => ' host=' . $config->dbHost . ' port=' . $config->dbPort . ' dbname=' . $config->dbName . ' user='******' password='******'', 'persistent' => $config->dbPersistent), $config->dbConnectionName);
     return $this;
 }
Exemplo n.º 2
0
 function startup()
 {
     parent::startup();
     //vypnutie debugeru + profileru
     $config = NEnvironment::getConfig()->database;
     $config->profiler = false;
     $config->lazy = false;
     dibi::connect($config);
     //NDebug::enable( TRUE, LOG_DIR);
 }
Exemplo n.º 3
0
 public function __construct($branch, $databaseName)
 {
     $this->_basedir = realpath(dirname(__FILE__) . '/../../../');
     require_once $this->_basedir . '/vendor/dg/dibi/dibi/dibi.php';
     $this->_databaseName = $databaseName;
     $this->_createJumpstormIni($branch);
     $this->_setUpEnv();
     $this->_verifyMagento($this->_pathToMagentoBaseDir);
     \dibi::connect(array('driver' => 'mysql', 'username' => 'root', 'database' => $this->_databaseName));
     file_put_contents($this->_getTagFileName(), '');
 }
Exemplo n.º 4
0
 public function init($options)
 {
     parent::init($options);
     $this->sqlDriver = AJXP_Utils::cleanDibiDriverParameters($options["SQL_DRIVER"]);
     try {
         dibi::connect($this->sqlDriver);
     } catch (DibiException $e) {
         echo get_class($e), ': ', $e->getMessage(), "\n";
         exit(1);
     }
 }
 /**
  * Initialise the driver.
  * 
  * Expects options containing a key 'SQL_DRIVER' with constructor values from dibi::connect()
  * 
  * Example:
  * 		"SQL_DRIVER" => Array(
  *		'driver' => 'sqlite',
  *			'file' => "./server/ajxp.db"
  *		)
  *
  * Example 2:
  * 		"SQL_DRIVER" => Array(
  * 		'driver' => 'mysql',
  * 		'host' => 'localhost',
  * 		'username' => 'root',
  * 		'password' => '***',
  * 		'database' => 'dbname'
  * 		)
  * 
  * @see server/classes/AbstractConfDriver#init($options)
  */
 function init($options)
 {
     parent::init($options);
     $this->sqlDriver = $options["SQL_DRIVER"];
     try {
         dibi::connect($this->sqlDriver);
     } catch (DibiException $e) {
         echo get_class($e), ': ', $e->getMessage(), "\n";
         exit(1);
     }
 }
 /**
  * Initialise the driver.
  *
  * Gives the driver a chance to set up it's connection / file resource etc..
  * 
  * @param Array $options array of options specific to the logger driver.
  * @access public
  */
 function init($options)
 {
     parent::init($options);
     require_once AJXP_BIN_FOLDER . "/dibi.compact.php";
     $this->sqlDriver = $options["SQL_DRIVER"];
     try {
         dibi::connect($this->sqlDriver);
     } catch (DibiException $e) {
         echo get_class($e), ': ', $e->getMessage(), "\n";
         exit(1);
     }
 }
Exemplo n.º 7
0
 /**
  * Initialize the driver.
  *
  * Gives the driver a chance to set up it's connection / file resource etc..
  *
  * @param Array $options array of options specific to the logger driver.
  * @access public
  */
 public function init($options)
 {
     parent::init($options);
     $this->sqlDriver = AJXP_Utils::cleanDibiDriverParameters($options["SQL_DRIVER"]);
     try {
         dibi::connect($this->sqlDriver);
     } catch (DibiException $e) {
         echo get_class($e), ': ', $e->getMessage(), "\n";
         exit(1);
     }
     $this->queries = AJXP_Utils::loadSerialFile($this->getBaseDir() . "/queries.json", false, "json");
 }
Exemplo n.º 8
0
 /**
  * Initialise the driver.
  *
  * Expects options containing a key 'SQL_DRIVER' with constructor values from dibi::connect()
  *
  * Example:
  * 		"SQL_DRIVER" => Array(
  *		'driver' => 'sqlite',
  *			'file' => "./server/ajxp.db"
  *		)
  *
  * Example 2:
  * 		"SQL_DRIVER" => Array(
  * 		'driver' => 'mysql',
  * 		'host' => 'localhost',
  * 		'username' => 'root',
  * 		'password' => '***',
  * 		'database' => 'dbname'
  * 		)
  *
  * @see AbstractConfDriver#init($options)
  */
 public function init($options)
 {
     parent::init($options);
     require_once AJXP_BIN_FOLDER . "/dibi.compact.php";
     $this->sqlDriver = AJXP_Utils::cleanDibiDriverParameters($options["SQL_DRIVER"]);
     try {
         dibi::connect($this->sqlDriver);
     } catch (DibiException $e) {
         //throw $e;
         echo get_class($e), ': ', $e->getMessage(), "\n";
         exit(1);
     }
 }
 function init($options)
 {
     parent::init($options);
     $this->sqlDriver = $options["SQL_DRIVER"];
     try {
         dibi::connect($this->sqlDriver);
     } catch (DibiException $e) {
         echo get_class($e), ': ', $e->getMessage(), "\n";
         exit(1);
     }
     $this->prefix = $options["PREFIX_TABLE"];
     $this->groupid = $options["FEU_GROUPID"];
     $this->usersSerFile = $options["USERS_FILEPATH"];
 }
Exemplo n.º 10
0
 public static function connect($settings = array(), $connection_name = null)
 {
     $config = Environment::getConfig();
     foreach ($config['database'] as $connection_name => $settings) {
         try {
             dibi::connect($settings, $connection_name);
             if ($settings['profiler'] == true) {
                 dibi::getProfiler()->setFile(APP_DIR . '/log/db.txt');
             }
         } catch (DibiException $e) {
             echo get_class($e), ': ', $e->getMessage(), "\n";
         }
     }
 }
Exemplo n.º 11
0
Arquivo: Db.php Projeto: allyse/allyse
 /**
  * Connect to DB, inherit credentials from constructor
  */
 private function connect()
 {
     $this->connectionId = 'DB_CONNECTION_' . md5(implode(',', $this->credentials));
     if (defined($this->connectionId) === FALSE) {
         $connection = dibi::connect($this->credentials, $this->connectionId);
         // Tracy panel
         if (TRACY === TRUE) {
             $panel = new Dibi\Bridges\Tracy\Panel();
             $panel->register($connection);
         }
         define($this->connectionId, TRUE);
     }
     $this->connection = dibi::getConnection($this->connectionId);
 }
Exemplo n.º 12
0
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     if ($actionName != "changes" || !isset($httpVars["seq_id"])) {
         return false;
     }
     require_once AJXP_BIN_FOLDER . "/dibi.compact.php";
     dibi::connect($this->sqlDriver);
     HTMLWriter::charsetHeader('application/json', 'UTF-8');
     $res = dibi::query("SELECT\n                [seq] , [ajxp_changes].[repository_identifier] , [ajxp_changes].[node_id] , [type] , [source] ,  [target] , [ajxp_index].[bytesize], [ajxp_index].[md5], [ajxp_index].[mtime], [ajxp_index].[node_path]\n                FROM [ajxp_changes]\n                LEFT JOIN [ajxp_index]\n                    ON [ajxp_changes].[node_id] = [ajxp_index].[node_id]\n                WHERE [ajxp_changes].[repository_identifier] = %s AND [seq] > %i\n                ORDER BY [ajxp_changes].[node_id], [seq] ASC", $this->computeIdentifier(ConfService::getRepository()), AJXP_Utils::sanitize($httpVars["seq_id"], AJXP_SANITIZE_ALPHANUM));
     echo '{"changes":[';
     $previousNodeId = -1;
     $previousRow = null;
     $order = array("path" => 0, "content" => 1, "create" => 2, "delete" => 3);
     $relocateAttrs = array("bytesize", "md5", "mtime", "node_path", "repository_identifier");
     foreach ($res as $row) {
         $row->node = array();
         foreach ($relocateAttrs as $att) {
             $row->node[$att] = $row->{$att};
             unset($row->{$att});
         }
         if ($row->node_id == $previousNodeId) {
             $previousRow->target = $row->target;
             $previousRow->seq = $row->seq;
             if ($order[$row->type] > $order[$previousRow->type]) {
                 $previousRow->type = $row->type;
             }
         } else {
             if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
                 echo json_encode($previousRow) . ",";
             }
             $previousRow = $row;
             $previousNodeId = $row->node_id;
         }
         $lastSeq = $row->seq;
         flush();
     }
     if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
         echo json_encode($previousRow);
     }
     if (isset($lastSeq)) {
         echo '], "last_seq":' . $lastSeq . '}';
     } else {
         $lastSeq = dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle();
         if (empty($lastSeq)) {
             $lastSeq = 1;
         }
         echo '], "last_seq":' . $lastSeq . '}';
     }
 }
Exemplo n.º 13
0
 /**
  * Factory for settings db host.
  * @param  class Translator
  * @param  callable
  * @return Form
  */
 public function databaseHostFactory($translator, callable $onSuccess)
 {
     $form = $this->forms->create($translator);
     $form->addText('host', 'install.db.host')->setRequired('install.form.empty');
     $form->addText('user', 'install.db.user')->setRequired('install.form.empty');
     $form->addText('password', 'install.db.pass');
     $form->addText('database', 'install.db.name')->setRequired('install.form.empty');
     $form->addText('prefix', 'install.db.prefix')->setAttribute('placeholder', 'ns_');
     // Database drivers.
     $drivers = ['mysql' => 'MySQL', 'mysqli' => 'MySQLi'];
     $form->addSelect('driver', 'install.db.driver', $drivers)->setRequired();
     $form->addSubmit('send', 'install.db.send');
     $form->onSuccess[] = function (Form $form, $values) use($onSuccess) {
         try {
             // Testing database connection.
             if (\dibi::connect($values)) {
                 // Parameters for generate config neon file.
                 $arr = ['extensions' => ['dibi' => 'Dibi\\Bridges\\Nette\\DibiExtension22'], 'dibi' => ['host' => $values->host, 'username' => $values->user, 'password' => $values->password, 'database' => $values->database, 'driver' => $values->driver, 'lazy' => TRUE, 'substitutes' => ['prefix' => $values->prefix]]];
                 // Generate and save the configuration file
                 $this->loader->save($arr, $this->dirs->getAppDir() . '/modules/app.db.neon');
                 // Removing the old cache for updating the configuration file.
                 FileSystem::delete($this->dirs->getTempDir() . '/cache/Nette.Configurator');
                 // Save the installation step into the cache.
                 $this->steps->setToCache(Steps::Step1, rand(1, 9));
                 // Save db prefix.
                 if ($values->prefix) {
                     $this->sessions->getSessionSection()->prefix = $values->prefix;
                 }
             }
         } catch (\Dibi\Exception $e) {
             // Server database type error.
             if ($e->getCode() == 0) {
                 $form->addError('install.db.driver.catch');
                 // Host server not found.
             } elseif ($e->getCode() == 2002) {
                 $form->addError('install.db.host.catch');
                 // The user or password was not verified.
             } elseif ($e->getCode() == 1045) {
                 $form->addError('install.db.auth.catch');
                 // The database name was not found
             } elseif ($e->getCode() == 1049) {
                 $form->addError('install.db.name.catch');
             }
             return;
         }
         $onSuccess();
     };
     return $form;
 }
Exemplo n.º 14
0
 public static function initialize()
 {
     $conf = Environment::getConfig('database');
     $connection = dibi::connect($conf[$conf->engine]);
     if ($conf->engine == 'sqlite') {
         $connection->getDriver()->registerFunction('regexp', 'Sqlite::regexp', 2);
     } elseif ($conf->engine == 'postgre') {
         dibi::addSubst('', '::');
     }
     if ($conf->profiler) {
         $profiler = is_numeric($conf->profiler) || is_bool($conf->profiler) ? new DibiProfiler(array()) : new $conf->profiler();
         $profiler->setFile(Environment::expand('%logDir%') . '/sql.log');
         $connection->setProfiler($profiler);
     }
 }
Exemplo n.º 15
0
 /**
  * @param array $connectionParams
  */
 public static function init(array $connectionParams)
 {
     if (!dibi::isConnected()) {
         try {
             $connection = dibi::connect(array('driver' => $connectionParams['driver'], 'host' => $connectionParams['host'], 'dsn' => 'mysql:host=' . $connectionParams['host'] . ';dbname=' . $connectionParams['db'] . '', 'persistent' => true, 'username' => $connectionParams['user'], 'password' => $connectionParams['pass'], 'database' => $connectionParams['db'], 'charset' => isset($connectionParams['charset']) ? $connectionParams['charset'] : 'utf8', 'result' => array('detectTypes' => true, 'formatDate' => "Y-m-d", 'formatDateTime' => 'Y-m-d H:i:s'), 'profiler' => array('run' => true), 'flags' => MYSQLI_CLIENT_COMPRESS));
             $panel = new Dibi\Bridges\Tracy\Panel();
             $panel->register($connection);
         } catch (DibiException $e) {
             dd($e->getMessage());
             $view = Core_View::getInstance();
             $view->setLayoutFile('$maintenance/db_connect.phtml');
             $view->displayLayout();
             die;
         }
     }
 }
Exemplo n.º 16
0
 public function run()
 {
     $app = new \Slim\Slim();
     $this->app = $app;
     GetAllHeadersService::fixMissingFunction();
     $app->add(new \Widgeto\Middleware\Authorization(getallheaders(), array('^\\/$' => 'GET', '^\\/[^.]*.html$' => 'GET', '^\\/rest\\/login\\/$' => 'POST')));
     \dibi::connect(DatabaseConfigService::getConfig());
     \dibi::getSubstitutes()->{''} = getenv("TABLE_PREFIX");
     new \Widgeto\Rest\LoginRest($app);
     new \Widgeto\Rest\LogoutRest($app);
     new \Widgeto\Rest\PageRest($app);
     new \Widgeto\Rest\TemplateRest($app);
     new \Widgeto\Rest\FileRest($app);
     new \Widgeto\Rest\UserRest($app);
     new \Widgeto\Rest\HomeRest($app);
     $app->run();
 }
 function init($options)
 {
     parent::init($options);
     $this->sqlDriver = $options["SQL_DRIVER"];
     try {
         dibi::connect($this->sqlDriver);
     } catch (DibiException $e) {
         echo get_class($e), ': ', $e->getMessage(), "\n";
         exit(1);
     }
     $this->secret = $options["SECRET"];
     $this->prefix = $options["PREFIX_TABLE"];
     $this->urls = array($options["LOGIN_URL"], $options["LOGOUT_URL"]);
     $this->slaveMode = true;
     $res = dibi::query("SELECT sitepref_value FROM [" . $this->prefix . "siteprefs] WHERE sitepref_name = 'FEUajaxplorer_mapi_pref_ajxp_auth_group'");
     $grp = $res->fetchSingle();
     $this->groupid = $grp;
     $res2 = dibi::query("SELECT sitepref_value FROM [" . $this->prefix . "siteprefs] WHERE sitepref_name = 'FEUajaxplorer_mapi_pref_ajxp_secret'");
     $sec = $res2->fetchSingle();
     $this->secret_cmsms = trim($sec);
 }
Exemplo n.º 18
0
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">

<style> html { background: url(data/arrow.png) no-repeat bottom right; height: 100%; } </style>

<h1>Tracy | dibi</h1>

<p>Dibi can log queries and dump variables to the <a href="http://tracy.nette.org">Tracy</a>.</p>

<?php 
if (@(!(include __DIR__ . '/../vendor/autoload.php'))) {
    die('Install dependencies using `composer install --dev`');
}
// enable Tracy
Tracy\Debugger::enable();
$connection = dibi::connect(array('driver' => 'sqlite3', 'database' => 'data/sample.s3db', 'profiler' => array('run' => TRUE)));
// add panel to debug bar
$panel = new Dibi\Bridges\Tracy\Panel();
$panel->register($connection);
// query will be logged
dibi::query('SELECT 123');
// result set will be dumped
Tracy\Debugger::barDump(dibi::fetchAll('SELECT * FROM customers WHERE customer_id < ?', 38), '[customers]');
Exemplo n.º 19
0
 /**
  * Helpers to test SQL connection and send a test email.
  * @param $action
  * @param $httpVars
  * @param $fileVars
  * @throws Exception
  */
 public function testConnexions($action, $httpVars, $fileVars)
 {
     $data = array();
     AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "DRIVER_OPTION_");
     if ($action == "boot_test_sql_connexion") {
         $p = AJXP_Utils::cleanDibiDriverParameters($data["db_type"]);
         if ($p["driver"] == "sqlite3") {
             $dbFile = AJXP_VarsFilter::filter($p["database"]);
             if (!file_exists(dirname($dbFile))) {
                 mkdir(dirname($dbFile), 0755, true);
             }
         }
         // Should throw an exception if there was a problem.
         dibi::connect($p);
         dibi::disconnect();
         echo 'SUCCESS:Connexion established!';
     } else {
         if ($action == "boot_test_mailer") {
             $mailerPlug = AJXP_PluginsService::findPluginById("mailer.phpmailer-lite");
             $mailerPlug->loadConfigs(array("MAILER" => $data["MAILER_ENABLE"]["MAILER_SYSTEM"]));
             $mailerPlug->sendMail(array("adress" => $data["MAILER_ENABLE"]["MAILER_ADMIN"]), "Pydio Test Mail", "Body of the test", array("adress" => $data["MAILER_ENABLE"]["MAILER_ADMIN"]));
             echo 'SUCCESS:Mail sent to the admin adress, please check it is in your inbox!';
         }
     }
 }
Exemplo n.º 20
0
{
    Debugger::barDump($x);
}
// Enable RobotLoader - this will load all classes automatically
$configurator->setTempDirectory(APP_DIR . '/temp');
$configurator->createRobotLoader()->addDirectory(APP_DIR)->addDirectory(LIBS_DIR)->register();
// Create Dependency Injection container from config.neon files
$configurator->addConfig(LIBS_DIR . '/npress/config.neon');
$configurator->addConfig(APP_DIR . '/config.neon');
$configurator->addConfig(WWW_DIR . '/data/config.neon');
if (file_exists(WWW_DIR . '/data/config.local.neon')) {
    $configurator->addConfig(WWW_DIR . '/data/config.local.neon');
}
$container = $configurator->createContainer();
// Connect to the database
dibi::connect($container->params['database']);
// Setup router
$container->router[] = $adminRouter = new RouteList('Admin');
$adminRouter[] = new Route('admin/<presenter>/<action>[/<id_page>]', 'Admin:default', isset($_SERVER['HTTPS']) ? Route::SECURED : false);
$container->router[] = $frontRouter = new RouteList('Front');
$frontRouter[] = new Route('data/thumbs/<id>[.<opts>].png', 'Files:preview');
$frontRouter[] = new Route('files[/<action>][/<id>]', 'Files:default');
$frontRouter[] = new Route('index.php', 'Pages:default', Route::ONE_WAY);
$frontRouter[] = new PagesRouter();
$frontRouter[] = new RedirectRouter();
$frontRouter[] = new Route('<presenter>[/<action>]/<id_page>', array('presenter' => 'Pages', 'action' => 'default', 'id_page' => 1));
// Include app specific bootstrap.php
if (file_exists(APP_DIR . '/bootstrap.php')) {
    require_once APP_DIR . '/bootstrap.php';
}
// Configure and run the application!
Exemplo n.º 21
0
<?php

/**
 * Základní nastavení, připojení k databázy s přednastavenými parametry.
 *
 * @author Kosek David
 */
define('DS', DIRECTORY_SEPARATOR);
define('SERVER_ROOT', dirname(__FILE__));
// debugování
error_reporting(E_ALL);
require_once '/lib/dibi.min.php';
dibi::connect(array('driver' => 'mysqli', 'host' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'kiv_web'));
Exemplo n.º 22
0
<?php

require './lib/dibi.min.php';
// DB
try {
    $dsn = new PDO("mysql:host=mysql1.alwaysdata.com;dbname=toto_logs", 'toto_logs', 'N-z@<S4#33;!58h', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    dibi::connect(array('driver' => 'pdo', 'pdo' => $dsn, 'lazy' => true, 'profiler' => array('run' => TRUE)));
    // $dibi = true;
} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}
Exemplo n.º 23
0
} catch (DibiException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}
echo "</p>\n";
// connects to MS SQL
echo '<p>Connecting to MS SQL: ';
try {
    dibi::connect(array('driver' => 'mssql', 'host' => 'localhost', 'username' => 'root', 'password' => 'xxx'));
    echo 'OK';
} catch (DibiException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}
echo "</p>\n";
// connects to MS SQL 2005
echo '<p>Connecting to MS SQL 2005: ';
try {
    dibi::connect(array('driver' => 'mssql2005', 'host' => '(local)', 'username' => 'Administrator', 'password' => 'xxx', 'database' => 'main'));
    echo 'OK';
} catch (DibiException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}
echo "</p>\n";
// connects to Oracle
echo '<p>Connecting to Oracle: ';
try {
    dibi::connect(array('driver' => 'oracle', 'username' => 'root', 'password' => 'xxx', 'database' => 'db'));
    echo 'OK';
} catch (DibiException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}
echo "</p>\n";
Exemplo n.º 24
0
// Configure application
$configurator = new Nette\Config\Configurator();
// Enable Nette Debugger for error visualisation & logging
$configurator->setProductionMode(false);
$configurator->enableDebugger();
// Enable RobotLoader - this will load all classes automatically
$configurator->setTempDirectory(__DIR__ . '/../../temp');
$configurator->createRobotLoader()->addDirectory(APP_DIR)->register();
// Create Dependency Injection container from config.neon file
$configurator->addConfig(__DIR__ . '/../config/config.neon');
$container = $configurator->createContainer();
$new = $old = array("driver" => "mysql", "host" => "localhost", "username" => "root", "password" => "root", "database" => "peknyden", "charset" => "utf8", "result:objects" => "", "format:date" => "Y-m-d", "format:datetime" => "Y-m-d H:i:s");
$old['database'] = 'peknyden_old';
//dibi::connect(Environment::getConfig('database'));
dibi::connect($new, "new");
dibi::connect($old, "old");
dibi::activate('new');
dibi::query('SET FOREIGN_KEY_CHECKS=0;');
//categories(); // kategorie - aktivity
subjects();
// subjekty - katalog
//files(); // soubory
//subject_files();
//localities(); // lokality
//shire(); // kraje
//events(); // eventy
/**
 * Subjects
 */
function subjects()
{
Exemplo n.º 25
0
 public static function runCreateTablesQuery($p, $file)
 {
     switch ($p["driver"]) {
         case "sqlite":
         case "sqlite3":
             if (!file_exists(dirname($p["database"]))) {
                 @mkdir(dirname($p["database"]), 0755, true);
             }
             $ext = ".sqlite";
             break;
         case "mysql":
             $ext = ".mysql";
             break;
         case "postgre":
             $ext = ".pgsql";
             break;
         default:
             return "ERROR!, DB driver " . $p["driver"] . " not supported yet in __FUNCTION__";
     }
     $result = array();
     $file = dirname($file) . "/" . str_replace(".sql", $ext, basename($file));
     $sql = file_get_contents($file);
     $separators = explode("/** SEPARATOR **/", $sql);
     $allParts = array();
     foreach ($separators as $sep) {
         $explode = explode("\n", trim($sep));
         $firstLine = array_shift($explode);
         if ($firstLine == "/** BLOCK **/") {
             $allParts[] = $sep;
         } else {
             $parts = explode(";", $sep);
             $remove = array();
             for ($i = 0; $i < count($parts); $i++) {
                 $part = $parts[$i];
                 if (strpos($part, "BEGIN") && isset($parts[$i + 1])) {
                     $parts[$i] .= ';' . $parts[$i + 1];
                     $remove[] = $i + 1;
                 }
             }
             foreach ($remove as $rk) {
                 unset($parts[$rk]);
             }
             $allParts = array_merge($allParts, $parts);
         }
     }
     dibi::connect($p);
     dibi::begin();
     foreach ($allParts as $createPart) {
         $sqlPart = trim($createPart);
         if (empty($sqlPart)) {
             continue;
         }
         try {
             dibi::nativeQuery($sqlPart);
             $resKey = str_replace("\n", "", substr($sqlPart, 0, 50)) . "...";
             $result[] = "OK: {$resKey} executed successfully";
         } catch (DibiException $e) {
             $result[] = "ERROR! {$sqlPart} failed";
         }
     }
     dibi::commit();
     dibi::disconnect();
     $message = implode("\n", $result);
     if (strpos($message, "ERROR!")) {
         return $message;
     } else {
         return "SUCCESS:" . $message;
     }
 }
 public function upgradeDB()
 {
     $confDriver = ConfService::getConfStorageImpl();
     $authDriver = ConfService::getAuthDriverImpl();
     $logger = AJXP_Logger::getInstance();
     if (is_a($confDriver, "sqlConfDriver")) {
         $conf = AJXP_Utils::cleanDibiDriverParameters($confDriver->getOption("SQL_DRIVER"));
         if (!is_array($conf) || !isset($conf["driver"])) {
             return "Nothing to do";
         }
         switch ($conf["driver"]) {
             case "sqlite":
             case "sqlite3":
                 $ext = ".sqlite";
                 break;
             case "postgre":
                 $ext = ".pgsql";
                 break;
             case "mysql":
                 $ext = is_file($this->workingFolder . "/" . $this->dbUpgrade . ".mysql") ? ".mysql" : ".sql";
                 break;
             default:
                 return "ERROR!, DB driver " . $conf["driver"] . " not supported yet in __FUNCTION__";
         }
         $file = $this->dbUpgrade . $ext;
         if (!is_file($this->workingFolder . "/" . $file)) {
             return "Nothing to do.";
         }
         $sqlInstructions = file_get_contents($this->workingFolder . "/" . $file);
         $parts = array_map("trim", explode("/* SEPARATOR */", $sqlInstructions));
         $results = array();
         $errors = array();
         dibi::connect($conf);
         dibi::begin();
         foreach ($parts as $sqlPart) {
             if (empty($sqlPart)) {
                 continue;
             }
             try {
                 dibi::nativeQuery($sqlPart);
                 $results[] = $sqlPart;
             } catch (DibiException $e) {
                 $errors[] = $sqlPart . " (" . $e->getMessage() . ")";
             }
         }
         dibi::commit();
         dibi::disconnect();
         if (!count($errors)) {
             return "Database successfully upgraded";
         } else {
             return "Database upgrade failed. <br>The following statements were executed : <br>" . implode("<br>", $results) . ",<br><br> The following statements failed : <br>" . implode("<br>", $errors) . "<br><br> You should manually upgrade your DB.";
         }
     }
 }
 /**
  * @param AJXP_Node $oldNode
  * @param AJXP_Node $newNode
  * @param bool $copy
  */
 public function updateNodesIndex($oldNode = null, $newNode = null, $copy = false)
 {
     if (!dibi::isConnected()) {
         dibi::connect($this->sqlDriver);
     }
     //$this->logInfo("Syncable index", array($oldNode == null?'null':$oldNode->getUrl(), $newNode == null?'null':$newNode->getUrl()));
     try {
         if ($newNode != null && $this->excludeNode($newNode)) {
             // CREATE
             if ($oldNode == null) {
                 AJXP_Logger::debug("Ignoring " . $newNode->getUrl() . " for indexation");
                 return;
             } else {
                 AJXP_Logger::debug("Target node is excluded, see it as a deletion: " . $newNode->getUrl());
                 $newNode = null;
             }
         }
         if ($newNode == null) {
             $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser());
             // DELETE
             $this->logDebug('DELETE', $oldNode->getUrl());
             dibi::query("DELETE FROM [ajxp_index] WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId);
         } else {
             if ($oldNode == null || $copy) {
                 // CREATE
                 $stat = stat($newNode->getUrl());
                 $newNode->setLeaf(!($stat['mode'] & 040000));
                 $this->logDebug('INSERT', $newNode->getUrl());
                 dibi::query("INSERT INTO [ajxp_index]", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath()), "bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => $newNode->isLeaf() ? md5_file($newNode->getUrl()) : "directory", "repository_identifier" => $repoId = $this->computeIdentifier($newNode->getRepository(), $newNode->getUser())));
             } else {
                 $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser());
                 if ($oldNode->getPath() == $newNode->getPath()) {
                     // CONTENT CHANGE
                     clearstatcache();
                     $stat = stat($newNode->getUrl());
                     $this->logDebug("Content changed", "current stat size is : " . $stat["size"]);
                     $this->logDebug('UPDATE CONTENT', $newNode->getUrl());
                     dibi::query("UPDATE [ajxp_index] SET ", array("bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => md5_file($newNode->getUrl())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId);
                     try {
                         $rowCount = dibi::getAffectedRows();
                         if ($rowCount === 0) {
                             $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!");
                             $this->updateNodesIndex(null, $newNode, false);
                         }
                     } catch (Exception $e) {
                     }
                 } else {
                     // PATH CHANGE ONLY
                     $newNode->loadNodeInfo();
                     if ($newNode->isLeaf()) {
                         $this->logDebug('UPDATE LEAF PATH', $newNode->getUrl());
                         dibi::query("UPDATE [ajxp_index] SET ", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId);
                         try {
                             $rowCount = dibi::getAffectedRows();
                             if ($rowCount === 0) {
                                 $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!");
                                 $this->updateNodesIndex(null, $newNode, false);
                             }
                         } catch (Exception $e) {
                         }
                     } else {
                         $this->logDebug('UPDATE FOLDER PATH', $newNode->getUrl());
                         dibi::query("UPDATE [ajxp_index] SET [node_path]=REPLACE( REPLACE(CONCAT('\$\$\$',[node_path]), CONCAT('\$\$\$', %s), CONCAT('\$\$\$', %s)) , '\$\$\$', '') ", $oldNode->getPath(), $newNode->getPath(), "WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId);
                         try {
                             $rowCount = dibi::getAffectedRows();
                             if ($rowCount === 0) {
                                 $this->logError(__FUNCTION__, "There was an update event on a non-indexed folder (" . $newNode->getPath() . "), relaunching a recursive indexation!");
                                 AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array());
                             }
                         } catch (Exception $e) {
                         }
                     }
                 }
             }
         }
     } catch (Exception $e) {
         AJXP_Logger::error("[meta.syncable]", "Exception", $e->getTraceAsString());
         AJXP_Logger::error("[meta.syncable]", "Indexation", $e->getMessage());
     }
 }
Exemplo n.º 28
0
<h1>dibi logger example</h1>
<?php 
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
dibi::connect(array('driver' => 'sqlite', 'database' => 'sample.sdb', 'profiler' => TRUE));
// enable log to this file
dibi::getProfiler()->setFile('log.sql');
try {
    $res = dibi::query('SELECT * FROM [customers] WHERE [customer_id] = %i', 1);
    $res = dibi::query('SELECT * FROM [customers] WHERE [customer_id] < %i', 5);
    $res = dibi::query('SELECT FROM [customers] WHERE [customer_id] < %i', 38);
} catch (DibiException $e) {
    echo '<p>', get_class($e), ': ', $e->getMessage(), '</p>';
}
echo "<h2>File log.sql:</h2>";
echo '<pre>', file_get_contents('log.sql'), '</pre>';
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">

<h1>Query Language & Conditions | dibi</h1>

<?php 
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
dibi::connect(array('driver' => 'sqlite3', 'database' => 'data/sample.s3db'));
// some variables
$cond1 = TRUE;
$cond2 = FALSE;
$foo = -1;
$bar = 2;
// conditional variable
$name = $cond1 ? 'K%' : NULL;
// if & end
dibi::test('
	SELECT *
	FROM customers
	%if', isset($name), 'WHERE name LIKE ?', $name, '%end');
// -> SELECT * FROM customers WHERE name LIKE 'K%'
// if & else & (optional) end
dibi::test("\r\n\tSELECT *\r\n\tFROM people\r\n\tWHERE id > 0\r\n\t\t%if", $foo > 0, "AND foo=?", $foo, "\r\n\t\t%else %if", $bar > 0, "AND bar=?", $bar, "\r\n");
// -> SELECT * FROM people WHERE id > 0 AND bar=2
// nested condition
dibi::test('
	SELECT *
	FROM customers
	WHERE
		%if', isset($name), 'name LIKE ?', $name, '
			%if', $cond2, 'AND admin=1 %end
Exemplo n.º 30
0
<style>
pre.dibi { padding-bottom: 10px; }
</style>
<h1>dibi conditional SQL example</h1>
<pre>
<?php 
require_once 'Nette/Debug.php';
require_once '../dibi/dibi.php';
dibi::connect(array('driver' => 'sqlite', 'database' => 'sample.sdb'));
$cond1 = TRUE;
$cond2 = FALSE;
$foo = -1;
$bar = 2;
$name = $cond1 ? 'K%' : NULL;
// if & end
dibi::test('
SELECT *
FROM [customers]
%if', isset($name), 'WHERE [name] LIKE %s', $name, '%end');
// -> SELECT * FROM [customers] WHERE [name] LIKE 'K%'
// if & else & (optional) end
dibi::test("\nSELECT *\nFROM [people]\nWHERE [id] > 0\n\t%if", $foo > 0, "AND [foo]=%i", $foo, "\n\t%else %if", $bar > 0, "AND [bar]=%i", $bar, "\n");
// -> SELECT * FROM [people] WHERE [id] > 0 AND [bar]=2
// nested condition
dibi::test('
SELECT *
FROM [customers]
WHERE
	%if', isset($name), '[name] LIKE %s', $name, '
		%if', $cond2, 'AND [admin]=1 %end
	%else 1 LIMIT 10 %end');