protected function execute(InputInterface $input, OutputInterface $output) { $fs = new Filesystem(); try { Capsule::connection("default")->setFetchMode(PDO::FETCH_NUM); $arr = Capsule::connection("default")->select('SHOW TABLES;'); foreach ($arr as $ts) { $name = $ts[0]; $output->writeln($name); // search for primary $sql1 = "SHOW INDEX from " . $name . " WHERE Key_name='PRIMARY';"; $pk1 = Capsule::connection("default")->select($sql1); if (count($pk1) > 0) { $pk = $pk1[0][4]; } else { // by first unique index $sql2 = "SHOW INDEX from " . $name . " WHERE Non_unique=0;"; $pk2 = Capsule::connection("default")->select($sql2); if (count($pk2) > 0) { $pk = $pk2[0][4]; } } $modelname = Stringy::create($name)->upperCamelize()->__toString(); $nmodel = $this->model; $nmodel = str_replace('##modelname##', $modelname, $nmodel); $nmodel = str_replace('##tablename##', $name, $nmodel); $nmodel = str_replace('##foreignkey##', $pk, $nmodel); $path = ROOT . DS . "app" . DS . "Application" . DS . "Models" . DS; $filename = $path . $modelname . ".php"; file_put_contents($filename, $nmodel); } } catch (\Exception $e) { $output->writeln('Error : ' . $e->getMessage()); } $output->writeln('finished'); }
/** * Register the Capsule service. * * @param Application $app **/ public function register(Application $app) { $app['capsule.connection_defaults'] = array('driver' => 'mysql', 'host' => 'localhost', 'database' => null, 'username' => 'root', 'password' => null, 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => null, 'logging' => false); $app['capsule.global'] = true; $app['capsule.eloquent'] = true; $app['capsule.container'] = $app->share(function () { return new Container(); }); $app['capsule.dispatcher'] = $app->share(function () use($app) { return new Dispatcher($app['capsule.container']); }); if (class_exists('Illuminate\\Cache\\CacheManager')) { $app['capsule.cache_manager'] = $app->share(function () use($app) { return new CacheManager($app['capsule.container']); }); } $app['capsule'] = $app->share(function ($name) use($app) { $capsule = new Capsule($app['capsule.container']); $capsule->setEventDispatcher($app['capsule.dispatcher']); if (isset($app['capsule.cache_manager']) && isset($app['capsule.cache'])) { $capsule->setCacheManager($app['capsule.cache_manager']); foreach ($app['capsule.cache'] as $key => $value) { $app['capsule.container']->offsetGet('config')->offsetSet('cache.' . $key, $value); } } if ($app['capsule.global']) { $capsule->setAsGlobal(); } if ($app['capsule.eloquent']) { $capsule->bootEloquent(); } if (!isset($app['capsule.connections'])) { $app['capsule.connections'] = array('default' => isset($app['capsule.connection']) ? $app['capsule.connection'] : array()); } foreach ($app['capsule.connections'] as $connection => $options) { $options = array_replace($app['capsule.connection_defaults'], $options); $logging = $options['logging']; unset($options['logging']); $capsule->addConnection($options, $connection); if ($logging) { $capsule->connection($connection)->enableQueryLog(); } else { $capsule->connection($connection)->disableQueryLog(); } } return $capsule; }); }
/** * For raw array fetching. Must be static, otherwise PHP gets confused about where to find the table_id. */ public static function queryBuilder() { // Set query builder to fetch result sets as associative arrays (instead of creating stdClass objects) Capsule::connection()->setFetchMode(\PDO::FETCH_ASSOC); $table = Database::getSchemaTable(static::$_table_id)->name; return Capsule::table($table); }
public function __construct() { $this->addCollector(new MessagesCollector()); $this->addCollector(new RequestDataCollector()); $this->addCollector(new TimeDataCollector()); $this->addCollector(new RouteDataCollector()); $this->addCollector(new ExceptionsCollector()); $values = \Parameters::get('redis'); $redis_enable = isset($values['default']['enable']) ? $values['default']['enable'] : 0; if ($redis_enable != 0) { $this->addCollector(new RedisDataCollector()); } try { $conn = Capsule::connection("default"); if ($conn != null) { $db = $conn->getPdo(); $pdo = new TraceablePDO($db); $this->addCollector(new PDOCollector($pdo)); } } catch (\Illuminate\Contracts\Container\BindingResolutionException $ex) { $this['exceptions']->addException($ex); } catch (\PDOException $e) { $this['exceptions']->addException($e); } }
protected function setUp() { $schema_sql = file_get_contents(TEST_SCHEMA_SQL); \Illuminate\Database\Capsule\Manager::connection()->getPdo()->exec($schema_sql); $createQuestion0 = new M_Question(); $createQuestion0->createQuestion('タイトル0', '問題文00', '選択肢01', '選択肢02', '選択肢03', '選択肢04', 4); $createQuestion00 = new M_Question(); $createQuestion00->createQuestion('タイトル00', '問題文00', '選択肢10', '選択肢20', '選択肢30', '選択肢40', 3); $createQuestion000 = new M_Question(); $createQuestion000->createQuestion('タイトル000', '問題文000', '選択肢100', '選択肢200', '選択肢300', '選択肢400', 3); $createQuestion0000 = new M_Question(); $createQuestion0000->createQuestion('タイトル0000', '問題文0000', '選択肢1000', '選択肢2000', '選択肢3000', '選択肢4000', 3); $createQuestion00000 = new M_Question(); $createQuestion00000->createQuestion('タイトル00000', '問題文00000', '選択肢10000', '選択肢20000', '選択肢30000', '選択肢40000', 3); $createQuestion000000 = new M_Question(); $createQuestion000000->createQuestion('タイトル000000', '問題文00000000', '選択肢10000000', '選択肢20000000', '選択肢30000000', '選択肢40000000', 3); $createQuestion0000000 = new M_Question(); $createQuestion0000000->createQuestion('タイトル0000000', '問題文0000000', '選択肢1000000', '選択肢2000000', '選択肢3000000', '選択肢4000000', 3); $createQuestion00000000 = new M_Question(); $createQuestion00000000->createQuestion('タイトル00000000', '問題文00000000', '選択肢10000000', '選択肢20000000', '選択肢30000000', '選択肢40000000', 3); $createQuestion000000000 = new M_Question(); $createQuestion000000000->createQuestion('タイトル000000000', '問題文000000000', '選択肢100000000', '選択肢200000000', '選択肢300000000', '選択肢400000000', 3); $createQuestion0000000000 = new M_Question(); $createQuestion0000000000->createQuestion('タイトル0000000000', '問題文0000000000', '選択肢1000000000', '選択肢2000000000', '選択肢3000000000', '選択肢4000000000', 3); $createQuestion999 = new M_Question(); $createQuestion999->createQuestion('タイトル999', '問題文999', '選択肢1999', '選択肢2999', '選択肢3999', '選択肢4999', 3); $quiz = new M_Quiz(); $title = 'クイズタイトルテスト0'; $quizlist = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //クイズを作成 $quizId = $quiz->createQuiz($title, $quizlist); }
/** * Sets up the session for the currently logged-in user, trying to re-establish a session for "remember-me" users who have been logged out, * or creates a guest user object if no one is logged in. */ public function setup() { try { // Initialize RememberMe $storage = new \Birke\Rememberme\Storage\PDO($this->app->remember_me_table); $storage->setConnection(\Illuminate\Database\Capsule\Manager::connection()->getPdo()); $this->app->remember_me = new \Birke\Rememberme\Authenticator($storage); // Change cookie path $cookie = $this->app->remember_me->getCookie(); $cookie->setPath("/"); $this->app->remember_me->setCookie($cookie); // Determine if we are already logged in (user exists in the session variable) if (isset($_SESSION["userfrosting"]["user_id"]) && $_SESSION["userfrosting"]["user_id"] != null) { // Load the user. If they don't exist any more, throw an exception. if (!($this->app->user = User::find($_SESSION["userfrosting"]["user_id"]))) { throw new AccountInvalidException(); } //error_log("Current user id is " . $this->app->user->id); // Check, if the Rememberme cookie exists and is still valid. // If not, we log out the current session if (!empty($_COOKIE[$this->app->remember_me->getCookieName()]) && !$this->app->remember_me->cookieIsValid()) { //error_log("Session expired. logging out..."); $this->app->remember_me->clearCookie(); throw new AuthExpiredException(); } // If not, try to login via RememberMe cookie } else { // If we can present the correct tokens from the cookie, log the user in // Get the user id $name = $this->app->remember_me->getCookieName(); $user_id = $this->app->remember_me->login(); if ($user_id) { //error_log("Logging in via remember me for $user_id"); // Load the user $this->app->user = \UserFrosting\UserLoader::fetch($user_id); // Update in session $_SESSION["userfrosting"]["user_id"] = $user_id; // There is a chance that an attacker has stolen the login token, so we store // the fact that the user was logged in via RememberMe (instead of login form) $_SESSION['remembered_by_cookie'] = true; } else { // If $rememberMe returned false, check if the token was invalid if ($this->app->remember_me->loginTokenWasInvalid()) { //error_log("Cookie was stolen!"); throw new AuthCompromisedException(); } else { // $rememberMe returned false because of invalid/missing Rememberme cookie - create a dummy "guest" user $this->app->user = new User([], $this->app->config('user_id_guest')); } } } // Now we have an authenticated user, setup their environment $this->app->setupAuthenticatedEnvironment(); } catch (\PDOException $e) { // If we can't connect to the DB, then we can't create an authenticated user. That's ok if we're in installation mode. error_log("Unable to authenticate user, falling back to guest user."); error_log($e->getTraceAsString()); } }
protected function configureDatabase() { $db = new DB(); $db->addConnection(array('driver' => 'sqlite', 'database' => ':memory:', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '')); $db->bootEloquent(); $db->setAsGlobal(); DB::connection()->enableQueryLog(); }
/** * Create Mycelium service and setup fake Facade */ protected function createMycelium() { $configurationData = (require __DIR__ . "/../../src/config/mycelium.php"); $config = new \Illuminate\Config\Repository(["mycelium" => $configurationData]); $connection = DB::connection(); $mycelium = new MyceliumManager($config, $connection); $mycelium->createAndRegisterDefaultMounters(); $mycelium->createAndRegisterDefaultParsers("Europe/Prague"); // initialize fake facade Mycelium::saveInstance($mycelium); }
function stripecx_link($params) { global $whmcs; $pdo = Capsule::connection()->getPdo(); # Invoice Variables $invoiceid = $params['invoiceid']; $description = $params["description"]; $amount = $params['amount']; # Format: ##.## $currency = $params['currency']; # Currency Code # Client Variables $email = $params['clientdetails']['email']; $postcode = $params['clientdetails']['postcode']; # System Variables $companyname = $params['companyname']; $systemurl = $params['systemurl']; # Config Options if ($params['validatezip'] == 'on') { $zipCodeValidation = 'true'; } else { $zipCodeValidation = 'false'; } if ($params['rememberme'] == 'on') { $RememberMe = 'true'; } else { $RememberMe = 'false'; } # Redirect If Checkout From Cart $cart = $_REQUEST['a']; if ($cart == 'complete') { header('Location: viewinvoice.php?id=' . $invoiceid . '&stripecx'); } # Auto-Start StripeCX? if (isset($_REQUEST['stripecx'])) { $start_sx = true; } else { $start_sx = false; } $sql = "SELECT * FROM stripecx_transactions WHERE invoice_id = '{$invoiceid}'"; $result = $pdo->query($sql); $row = $result->fetch(PDO::FETCH_ASSOC); if ($row) { $pending_trans = "\n\t\t<script>\n\t\t\t\$(document).ready(function() {\n\t\t\t\t\$('select[name=\"gateway\"]').attr('disabled', 'disabled');\n\t\t\t\t\$('#StripeCXbutton').attr('disabled', 'disabled');\n\t\t\t\t\$('#StripeCXbutton').text('" . $whmcs->get_lang('clientareapending') . "');\n\t\t\t});\n\t\t\t\n\t\t\tfunction submit() {\n\t\t\t\t\t\n\t\t\t}\n\t\t</script>\n\t\t\n\t\t"; } else { $pending_trans = NULL; } # Enter your code submit to the gateway... $code = "\n\t<script src=\"https://checkout.stripe.com/v2/checkout.js\"></script>\n\t<script src=\"assets/js/jquery.js\"></script>\n\t\n\t" . $pending_trans . "\n\t<form>\n\t<button id=\"StripeCXbutton\">" . $params['langpaynow'] . "</button>\n</form>\n\t<script>\n\t\$ = jQuery;\t\t\n\t\n\t\tvar handler = StripeCheckout.configure({\n\t\t\tkey: '" . $params['public-key'] . "',\n\t\t\timage: '" . $params['image-url'] . "',\n\t\t\tcurrency: '" . $currency . "',\n\t\t\temail: '" . $email . "',\n\t\t\tzipCode: '" . $zipCodeValidation . "',\n\t\t\tallowRememberMe: '" . $RememberMe . "',\n\t\t\tdescription: '" . str_replace($companyname . " - ", "", $description) . "',\n\t\t\ttoken: function(token) {\n\t\t\t\t// Use the token to create the charge with a server-side script.\n\t\t\t\t// You can access the token ID with `token.id`\n\t\t\t\t\n\t\t\t\t\$('select[name=\"gateway\"]').attr('disabled', 'disabled');\n\t\t\t\t\$('#StripeCXbutton').attr('disabled', 'disabled');\n\t\t\t\t\$('#StripeCXbutton').text('" . $whmcs->get_lang('clientareapending') . "');\n\t\t\t\t\n\t\t\t\tstoreTransaction('" . $invoiceid . "',token.id, '" . $currency . "', '" . $amount * 100 . "');\n\t\t\t}\n\t\t});\n\t\t\n\t\tdocument.getElementById('StripeCXbutton').addEventListener('click', function(e) {\n\t\t\t// Open Checkout with further options\n\t\t\thandler.open({\n\t\t\t\tname: '" . $companyname . "',\n\t\t\t\tdescription: '" . str_replace($companyname . " - ", "", $description) . "',\n\t\t\t\tamount: " . $amount * 100 . "\n\t\t\t});\n\t\t\te.preventDefault();\n\t\t});\n\t\t \n\t\tfunction storeTransaction(sid,stoken,currency, amount) {\n\t\t\t \n\t\t\turl = document.URL;\n\t\t\turl = url.substring(0, url.lastIndexOf('/') + 1);\n\t\t\t \n\t\t\t\$.ajax({\n\t\t\t\tdata: { id: sid, token: stoken, currency: currency, amount: amount },\n\t\t\t\turl: url+'modules/gateways/stripecx/callback.php',\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tsuccess: function(data) {\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t</script>\n\t"; if ($start_sx == true) { $code = $code . "\n\t\t<script>\n\t\t\tdocument.getElementById('StripeCXbutton').click();\n\t\t</script>\n\t\t"; } return $code; }
/** * create connection to the database based on given configuration */ private function makeConnection($config) { try { $capsule = new Capsule(); $capsule->addConnection($config); $capsule->setAsGlobal(); $capsule->bootEloquent(); Sentry::setupDatabaseResolver($capsule->connection()->getPdo()); } catch (Exception $e) { throw $e; } }
/** * Are we connected? * * @return bool */ public function IsConnected() { /** * Try (So we return a bool no matter what and don't crash and burn ahhh) */ try { /** * If we can get our database name */ if ($this->capsule->connection()->getDatabaseName()) { return true; } /** * Else, return false */ return false; } catch (\Exception $error) { /** * Just incase we error */ return false; } }
/** * Register the Capsule service. * * @param Silex\Application $app * @return void **/ public function register(Application $app) { $app['capsule.connection_defaults'] = ['driver' => 'mysql', 'host' => 'localhost', 'database' => null, 'username' => 'root', 'password' => null, 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => null, 'logging' => false]; $app['capsule.global'] = true; $app['capsule.eloquent'] = true; $app['capsule.container'] = $app->share(function () { return new Container(); }); $app['capsule.dispatcher'] = $app->share(function () use($app) { return new Dispatcher($app['capsule.container']); }); $app['capsule'] = $app->share(function ($app) { $capsule = new Capsule($app['capsule.container']); $capsule->setEventDispatcher($app['capsule.dispatcher']); if ($app['capsule.global']) { $capsule->setAsGlobal(); } if ($app['capsule.eloquent']) { $capsule->bootEloquent(); } if (!isset($app['capsule.connections'])) { $app['capsule.connections'] = ['default' => isset($app['capsule.connection']) ? $app['capsule.connection'] : []]; } foreach ($app['capsule.connections'] as $connection => $options) { $options = array_replace($app['capsule.connection_defaults'], $options); $logging = $options['logging']; unset($options['logging']); $capsule->addConnection($options, $connection); if ($logging) { $capsule->connection($connection)->enableQueryLog(); } else { $capsule->connection($connection)->disableQueryLog(); } } return $capsule; }); }
public function getColumnsNames(array $arAdditionalField = []) { if ($this->allFields) { return $this->allFields; } /* $connection = DB::connection(); $connection->getSchemaBuilder(); $results = $connection->select('PRAGMA table_info('.$this->table.')'); $results = $connection->getPostProcessor()->processColumnListing($results); */ $results = DB::connection()->getSchemaBuilder()->getColumnListing($this->table); $this->allFields = array_merge($results, $arAdditionalField); return $this->allFields; }
/** * Register Eloquent database in Slim app (use Model now) * * @return Shiniwork $this */ protected function registerDatabase() { $container = $this->getContainer(); $settings = $container->get('settings'); if (!empty($settings['database'])) { $capsule = new Manager(); $capsule->addConnection($settings['database']); $capsule->setAsGlobal(); $capsule->bootEloquent(); if ($container->getMode() === 'development') { $capsule->connection()->enableQueryLog(); } } return $this; }
/** * Register the Illuminate Database service * * @param Silex\Application */ public function register(Application $app) { $app['db.connection_defaults'] = array('driver' => 'mysql', 'host' => 'localhost', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => null); $app['db.boot'] = true; $app['db.global'] = true; $app['db.container'] = $app->share(function () { return new Container(); }); $app['db.dispatcher'] = $app->share(function () use($app) { return new Dispatcher($app['db.container']); }); if (class_exists('\\Illuminate\\Cache\\CacheManager')) { $app['db.cache_manager'] = $app->share(function () use($app) { return new \Illuminate\Cache\CacheManager($app['db.container']); }); } $app['db.cache'] = array('driver' => 'apc', 'prefix' => 'laravel'); $app['db'] = $app->share(function () use($app) { $db = new Capsule($app['db.container']); $db->setEventDispatcher($app['db.dispatcher']); if (isset($app['db.cache_manager']) && isset($app['db.cache'])) { $db->setCacheManager($app['db.cache_manager']); foreach ($app['db.cache'] as $key => $value) { $app['db.container']->offsetGet('config')->offsetSet('cache.' . $key, $value); } } if ($app['db.global']) { $db->setAsGlobal(); } if ($app['db.boot']) { $db->bootEloquent(); } if (!isset($app['db.connections'])) { $connection = array(); if (isset($app['db.connection'])) { $connection = $app['db.connection']; } $app['db.connections'] = array('default' => $connection); } foreach ($app['db.connections'] as $connection => $options) { $db->addConnection(array_replace($app['db.connection_defaults'], $options), $connection); } if (!$app['debug']) { $db->connection()->disableQueryLog(); } return $db; }); }
public function assertTreeNotBroken($table = 'categories') { $checks = array(); // Check if lft and rgt values are ok $checks[] = "from {$table} where _lft >= _rgt or (_rgt - _lft) % 2 = 0"; // Check if lft and rgt values are unique $checks[] = "from {$table} c1, {$table} c2 where c1.id <> c2.id and " . "(c1._lft=c2._lft or c1._rgt=c2._rgt or c1._lft=c2._rgt or c1._rgt=c2._lft)"; // Check if parent_id is set correctly $checks[] = "from {$table} c, {$table} p, {$table} m where c.parent_id=p.id and m.id <> p.id and m.id <> c.id and " . "(c._lft not between p._lft and p._rgt or c._lft between m._lft and m._rgt and m._lft between p._lft and p._rgt)"; foreach ($checks as $i => $check) { $checks[$i] = 'select 1 as error ' . $check; } $sql = 'select max(error) as errors from (' . implode(' union ', $checks) . ') _'; $actual = (array) Capsule::connection()->selectOne($sql); $this->assertEquals(array('errors' => null), $actual, "The tree structure of {$table} is broken!"); }
/** * 初始化 * * @author Seven Du <*****@*****.**> **/ protected static function init() { self::$_root = dirname(__FILE__); /* # 设置时区 */ if (function_exists('date_default_timezone_set')) { date_default_timezone_set('Asia/Shanghai'); } /* 初始化数据库 */ self::$capsule = new Capsule(); self::$capsule->addConnection((array) (include TS_CONFIGURE . '/database.php')); self::$capsule->setEventDispatcher(new Dispatcher(new Container())); // Make this Capsule instance available globally via static methods... (optional) self::$capsule->setAsGlobal(); // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher()) self::$capsule->bootEloquent(); // 关闭日志功能 self::$capsule->connection()->disableQueryLog(); }
public function testBuildTreePrunesAndInserts() { $tree = array(array('id' => 1, 'name' => 'A'), array('id' => 2, 'name' => 'B'), array('id' => 3, 'name' => 'C', 'children' => array(array('id' => 4, 'name' => 'C.1', 'children' => array(array('id' => 5, 'name' => 'C.1.1'), array('id' => 6, 'name' => 'C.1.2'))), array('id' => 7, 'name' => 'C.2'), array('id' => 8, 'name' => 'C.3'))), array('id' => 9, 'name' => 'D')); $this->assertTrue(Category::buildTree($tree)); $this->assertTrue(Category::isValidNestedSet()); // Postgres fix if (DB::connection()->getDriverName() === 'pgsql') { $tablePrefix = DB::connection()->getTablePrefix(); $sequenceName = $tablePrefix . 'categories_id_seq'; DB::connection()->statement('ALTER SEQUENCE ' . $sequenceName . ' RESTART WITH 10'); } $updated = array(array('id' => 1, 'name' => 'A'), array('id' => 2, 'name' => 'B'), array('id' => 3, 'name' => 'C', 'children' => array(array('id' => 4, 'name' => 'C.1', 'children' => array(array('id' => 5, 'name' => 'C.1.1'), array('id' => 6, 'name' => 'C.1.2'))), array('id' => 7, 'name' => 'C.2', 'children' => array(array('name' => 'C.2.1'), array('name' => 'C.2.2'))))), array('id' => 9, 'name' => 'D')); $this->assertTrue(Category::buildTree($updated)); $this->assertTrue(Category::isValidNestedSet()); $expected = array(array('id' => 1, 'name' => 'A'), array('id' => 2, 'name' => 'B'), array('id' => 3, 'name' => 'C', 'children' => array(array('id' => 4, 'name' => 'C.1', 'children' => array(array('id' => 5, 'name' => 'C.1.1'), array('id' => 6, 'name' => 'C.1.2'))), array('id' => 7, 'name' => 'C.2', 'children' => array(array('id' => 10, 'name' => 'C.2.1'), array('id' => 11, 'name' => 'C.2.2'))))), array('id' => 9, 'name' => 'D')); $hierarchy = Category::all()->toHierarchy()->toArray(); $this->assertArraysAreEqual($expected, array_ints_keys(hmap($hierarchy, array('id', 'name')))); }
public function register(Application $app) { // boot Eloquent $defaultConn = $app->getConfig('db.default'); $capsule = new Capsule(); $capsule->addConnection($app->getConfig("db.connections.{$defaultConn}")); $capsule->setAsGlobal(); $capsule->bootEloquent(); $capsule->connection(); // register Database in container $app->set("Database", function ($name = null) use($app) { $name = $name ?: $app->getConfig('db.default'); $config = $app->getConfig("db.connections.{$name}"); $capsule = new Capsule(); $capsule->addConnection($config, $name); return $capsule->getConnection($name); }); }
public function testRawQueries() { // Insert $inserted = Capsule::insert('INSERT INTO articles (title) VALUES (:title)', ['title' => static::ARTICLE_TITLE]); $this->assertTrue($inserted); // Last Insert ID $id = Capsule::connection()->getPdo()->lastInsertId(); $this->assertEquals(1, $id); // Select $articles = Capsule::select('SELECT * FROM articles WHERE id = ?', [$id]); $this->assertCount(1, $articles); $this->assertEquals($articles[0]->title, static::ARTICLE_TITLE); // Delete $deleted = Capsule::delete('DELETE FROM articles WHERE id = ?', [$id]); $this->assertEquals(1, $deleted); // Count $count = Capsule::selectOne('SELECT COUNT(*) as nb FROM articles'); $this->assertEquals(0, $count->nb); }
/** * Collect data about our connections and queries * * @param Request $request * @param Response $response * @param Exception $exception * @return void */ public function collect(Request $request, Response $response, \Exception $exception = null) { $this->data = array('activeConnectionCount' => 0, 'connectionCount' => count($this->connections), 'queries' => array(), 'queryCount' => 0, 'queryTime' => 0); // If we haven't made any database connections, don't do any processing if (count($this->connections)) { foreach ($this->connections as $connection) { $connection = Capsule::connection($connection->getName()); // Log an active connection as long as we have queries if (count($connection->getQueryLog())) { ++$this->data['activeConnectionCount']; } // Group queries by connection, add the over count and time to totals $this->data['queries'][$connection->getName()] = $connection->getQueryLog(); $this->data['queryCount'] += count($connection->getQueryLog()); foreach ($connection->getQueryLog() as $query) { $this->data['queryTime'] += $query['time']; } } } }
public function anySaveSorting() { $this->layout = false; $data = Arr::get($this->getPostData(), 'data'); //В качестве ответа выводим окно логина $response = 'Unfaithful Categories Sorting'; if (!empty($data)) { $data = json_decode($data, true); $article = new ArticleModel(); if (!empty($data)) { Capsule::connection()->transaction(function () use($data, $article, &$response) { foreach ($data as $item) { $article::find($item['id'])->update(['parent_id' => $item['parent_id'], 'lvl' => $item['depth'], 'lft' => $item['left'], 'rgt' => $item['right']]); } $response = 'Categories Sorting has successfully saved'; }); } } Message::instance()->info($response); echo Message::instance()->flash_all(); }
/** * Run the migrations. * * @return void */ public function up() { if ($connection = Capsule::connection($this->getConnection())) { $connection->useDefaultSchemaGrammar(); } else { $app = app(); $connection = $app['db']->connection($this->getConnection()); } $schema = new Schema($connection); if (!$schema->hasTable('salesforce_tokens')) { $schema->create('salesforce_tokens', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('access_token'); $table->string('refresh_token'); $table->string('instance_base_url'); $table->bigInteger('user_id'); $table->datetime('expires')->nullable(); $table->timestamps(); $table->softDeletes(); }); } }
public function scopePopular($query, $limit = 6) { $prefix = getenv('PORTAL_DB_PREFIX') ?: ''; return $query->select($this->getTable() . '.*')->addSelect(DB::connection('portal')->raw("COUNT({$prefix}va.id) AS visitor"))->join('visitor_artikel AS va', 'va.artikel_id', '=', $this->getTable() . '.id')->groupBy($this->getTable() . '.id')->orderBy('visitor', 'desc'); }
case 'DOUBLE': case 'DECIMAL': $type = 'DOUBLE'; break; case 'DATE': $type = 'DATE'; break; } return $type; }); $twig->addFilter($hiveFilter); $dbName = Capsule::connection()->getDatabaseName(); $db = new DB($dbName); $query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" . Capsule::connection()->getDatabaseName() . "'"; $tb_objs = Capsule::select($query); foreach ($tb_objs as $tb_obj) { $table = new Table($tb_obj); $columns = Capsule::select("select * from information_schema.COLUMNS where table_name = '" . $table->name . "' and TABLE_SCHEMA = '" . $dbName . "'"); foreach ($columns as $column_obj) { $column = new Column($column_obj); $table->columns[] = $column; } $fks = Capsule::select("select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME like 'fk_%' and table_name = '" . $table->name . "' and TABLE_SCHEMA ='" . Capsule::connection()->getDatabaseName() . "'"); foreach ($fks as $fk) { $table->foreignKeys[] = $fk->REFERENCED_TABLE_NAME; } $db->tables[] = $table; $db->tables[$table->name] = $table; } print $twig->render($params, ['db' => $db]); print "\n";
/** * Down * * @param Migration $migration * @return AdapterInterface */ public function down(Migration $migration) { $this->adapter->connection()->table($this->tableName)->where('version', $migration->getVersion())->delete(); return $this; }
/** * Get a list of all queries formatted with their bindings in place * * @param string $connection * @return array */ public static function getPrettyQueryLog($connection = "") { $return_queries = []; $queries = Capsule::connection($connection)->getQueryLog(); foreach ($queries as $query) { $query_pattern = str_replace('?', "'%s'", $query['query']); $return_queries[] = vsprintf($query_pattern, $query['bindings']); } return $return_queries; }
/** * Get a schema builder instance. * * @param string $connection * @return \Illuminate\Database\Schema\Builder */ public static function schema($connection = null) { return static::$instance->connection($connection)->getSchemaBuilder(); }
public function run() { DB::table('categories')->delete(); OrderedScopedCategory::unguard(); OrderedScopedCategory::create(array('id' => 1, 'company_id' => 1, 'name' => 'Root 1', 'lft' => 1, 'rgt' => 10, 'depth' => 0)); OrderedScopedCategory::create(array('id' => 2, 'company_id' => 1, 'name' => 'Child 3', 'lft' => 8, 'rgt' => 9, 'depth' => 1, 'parent_id' => 1)); OrderedScopedCategory::create(array('id' => 3, 'company_id' => 1, 'name' => 'Child 2', 'lft' => 4, 'rgt' => 7, 'depth' => 1, 'parent_id' => 1)); OrderedScopedCategory::create(array('id' => 4, 'company_id' => 1, 'name' => 'Child 2.1', 'lft' => 5, 'rgt' => 6, 'depth' => 2, 'parent_id' => 3)); OrderedScopedCategory::create(array('id' => 5, 'company_id' => 1, 'name' => 'Child 1', 'lft' => 2, 'rgt' => 3, 'depth' => 1, 'parent_id' => 1)); OrderedScopedCategory::create(array('id' => 6, 'company_id' => 2, 'name' => 'Root 2', 'lft' => 1, 'rgt' => 10, 'depth' => 0)); OrderedScopedCategory::create(array('id' => 7, 'company_id' => 2, 'name' => 'Child 4', 'lft' => 2, 'rgt' => 3, 'depth' => 1, 'parent_id' => 6)); OrderedScopedCategory::create(array('id' => 8, 'company_id' => 2, 'name' => 'Child 5', 'lft' => 4, 'rgt' => 7, 'depth' => 1, 'parent_id' => 6)); OrderedScopedCategory::create(array('id' => 9, 'company_id' => 2, 'name' => 'Child 5.1', 'lft' => 5, 'rgt' => 6, 'depth' => 2, 'parent_id' => 8)); OrderedScopedCategory::create(array('id' => 10, 'company_id' => 2, 'name' => 'Child 6', 'lft' => 8, 'rgt' => 9, 'depth' => 1, 'parent_id' => 6)); OrderedScopedCategory::reguard(); if (DB::connection()->getDriverName() === 'pgsql') { $tablePrefix = DB::connection()->getTablePrefix(); $sequenceName = $tablePrefix . 'categories_id_seq'; DB::connection()->statement('ALTER SEQUENCE ' . $sequenceName . ' RESTART WITH 11'); } }
/** * Log this user out. * * Destroys the PHP session as well. * @param bool $complete If set to true, will also clear out any persistent sessions. */ public function logout($complete = false) { if ($complete) { $storage = new \Birke\Rememberme\Storage\PDO(static::$app->remember_me_table); $storage->setConnection(\Illuminate\Database\Capsule\Manager::connection()->getPdo()); $storage->cleanAllTriplets($this->id); } // Change cookie path $cookie = static::$app->remember_me->getCookie(); $cookie->setPath("/"); static::$app->remember_me->setCookie($cookie); if (static::$app->remember_me->clearCookie()) { error_log("Cleared cookie"); } session_regenerate_id(true); session_destroy(); }