/** * Handle the command * * @return mixed */ public function fire() { try { /** @var Connection $_db */ /** @noinspection PhpUndefinedMethodInspection */ $_db = DB::connection($this->database); } catch (\Exception $_ex) { throw new \InvalidArgumentException('The database "' . $this->database . '" is invalid.'); } $_database = $this->database; $this->_v('* connected to database <info>' . $_database . '</info>.'); $_tablesWanted = $this->option('tables'); if (!empty($_tablesWanted)) { $_list = explode(',', $_tablesWanted); $_tablesWanted = empty($_list) ? false : ($_tablesWanted = $_list); $this->_vv('* ' . count($_tablesWanted) . ' table(s) will be scanned.'); } else { $this->_vv('* all tables will be scanned.'); } $_sm = $_db->getDoctrineSchemaManager(); $_tableNames = $_sm->listTableNames(); $this->_writeln('* examining ' . count($_tableNames) . ' table(s)...'); foreach ($_tableNames as $_tableName) { if ($_tablesWanted && !in_array($_tableName, $_tablesWanted)) { $this->_vvv(' * SKIP table <comment>' . $_tableName . '</comment>.'); continue; } $this->_v(' * SCAN table <info>' . $_tableName . '</info>.'); if ($this->_examineTable($_sm->listTableDetails($_tableName))) { $this->_writeln(' * <info>' . $_tableName . '</info> complete.'); } } return true; }
/** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->call(function () { $players = DB::connection('game')->table('player_characters')->get(); foreach ($players as $player) { if (!Player::where('id', $player->id)->exists()) { $player_info = ['id' => $player->id, 'name' => $player->given_name, 'level' => $player->level, 'class' => 0, 'gold' => $player->gold, 'family_name' => $player->family_id ? DB::connection('game')->table('family')->where('id', $player->family_id)->first()->name : '-']; Player::create($player_info); } } })->everyTenMinutes(); $schedule->call(function () { $families = DB::connection('game')->table('family')->get(); foreach ($families as $family) { if (!Family::where('id', $family->id)->exists()) { $gold = 0; foreach (DB::connection('game')->table('player_characters')->where('family_id', $family->id)->get() as $player) { $gold += $player->gold; } $family_info = ['id' => $family->id, 'name' => $family->name, 'level' => $family->lv, 'gold' => $gold, 'members' => DB::connection('game')->table('player_characters')->where('family_id', $family->id)->count(), 'leader' => DB::connection('game')->table('player_characters')->where('id', $family->leader_id)->first()->given_name]; Family::create($family_info); } } })->everyTenMinutes(); }
/** * Execute the console command. * * @return mixed */ public function fire(Almaty $almaty, Astana $astana) { $city = $this->option('city'); if ($city == 1) { $this->city = $almaty; } else { $this->city = $astana; } if ($this->city->obman_gps == "0") { return false; } $results = DB::connection($this->city->db)->table('cars')->join('crews', 'crews.car', '=', 'cars.id')->join('crews_inline as ci', 'crews.id', '=', 'ci.id')->join('wialon_cars as wi', 'cars.gn', '=', 'wi.gn')->where('ci.status', '=', 'waiting')->select('crews.driver', 'cars.gn', 'crews.id', 'ci.status', 'wi.pos_x AS wi_lon', 'wi.pos_y AS wi_lat', 'ci.lat AS tm_lat', 'ci.lon AS tm_lon')->get(); if (!empty($results)) { foreach ($results as $v) { if (isset($v->tm_lat) && isset($v->tm_lon) && isset($v->wi_lat) && isset($v->wi_lon)) { $diff = Helpers::distance($v->tm_lat, $v->tm_lon, $v->wi_lat, $v->wi_lon) / 1000; $diff = round($diff, 1); if ($diff >= 4.5) { if (isset($v->driver)) { $tm_address = Helpers::get_address_by_coords($v->tm_lat, $v->tm_lon); $wialon_address = Helpers::get_address_by_coords($v->wi_lat, $v->wi_lon); $this->call('drivers:operations', ['driver' => $v->driver, 'op' => 0, 'summ' => $this->city->obman_gps_price, 'reason' => 'Обман GPS', 'time' => time(), 'comment' => "ТМ Адрес: {$tm_address}, Wialon Адрес: {$wialon_address} Разница: {$diff} км", '--city' => $city]); } } } } } }
public function createTable($table) { // drop existing table DB::statement("drop table if exists `{$table}`"); $header = $this->request->getHeader(); $listings = $this->getListings(); $fields = []; foreach ($listings as $listing) { unset($listing->datajoeEntity); foreach ($listing as $k => $v) { if (isset($fields[$k])) { $fields[$k] = strlen(print_r($v, TRUE)) > $fields[$k] ? strlen(print_r($v, TRUE)) + 100 : $fields[$k]; } else { $fields[$k] = strlen(print_r($v, TRUE)) + 100; } } } $sql = "CREATE TABLE IF NOT EXISTS `{$table}` (\n\t\t\t`id` MEDIUMINT( 10 ) UNSIGNED NOT NULL,\n\t\t\t`name` VARCHAR( 100 ) NOT NULL COMMENT 'Name',\n"; foreach ($fields as $k => $v) { if ($k != 'name' && $k != 'id') { $sql .= "`{$k}` VARCHAR( {$v} ) NOT NULL COMMENT " . str_replace('?', '?', DB::connection()->getPdo()->quote($header->{$k}->label)) . ",\n"; } } $sql .= "FULLTEXT KEY `name` (`name`),\n\t\t\tPRIMARY KEY ( `id` )\n\t\t\t) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci;"; DB::statement($sql); }
/** * Execute the console command. * * @return mixed */ public function fire() { $this->info('Begin: ' . date('H:i:s')); DB::connection('mysql')->table('snapshot')->truncate(); $query = "insert into snapshot {$this->getQuery(1, false)}"; DB::connection('mysql')->statement($query); $result = DB::connection('mysql')->select($this->getQuery(2, true)); $rows = $result[0]->total; $this->info("Total de filas: {$rows}"); $begin = 0; $block = 15000; $countBlock = 1; $fCsv = storage_path('app/snapshots/' . date('Ymd') . '.csv'); if (file_exists($fCsv)) { unlink($fCsv); } $fp = fopen($fCsv, 'w'); fputs($fp, "estado,emisor,nombre,organizacion,dni,ruc,codigo,solicitud,fecha_solicitud,fecha_anulado,fecha_gencer,fecha_revocado,fecha_expira \n"); while ($rows > $begin) { $result = DB::connection('mysql')->select($this->getQuery(2, false, $begin, $block)); foreach ($result as $key => $value) { $resultArray = json_decode(json_encode($value), true); fputs($fp, str_replace("\n", '', implode($resultArray, ',')) . "\n"); } $this->info("End block {$countBlock}: " . date('H:i:s')); $begin += $block; $countBlock++; } fclose($fp); $this->info('End export to csv: ' . date('H:i:s')); $this->info('End: ' . date('H:i:s')); }
/** * Run the database seeds. * * @return void */ public function run() { foreach ($this->dumpFiles() as $dumpPart) { $query = "LOAD DATA LOCAL INFILE '" . str_replace('\\', '/', $dumpPart) . "'\n INTO TABLE `" . Config::citiesTableName() . "` \n FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\n LINES TERMINATED BY '\n' IGNORE 1 LINES\n (country,\n city_ascii,\n city,\n region,\n population,\n latitude,\n longitude\n )"; DB::connection()->getpdo()->exec($query); } }
public static function queryComment($model) { try { $results = DB::connection('mysql_system')->select('select COLUMN_NAME,COLUMN_COMMENT FROM columns WHERE table_schema = ? AND table_name = ?', [env('DB_DATABASE'), with($model)->getTable()]); } catch (\Exception $ex) { return []; } $column_names = []; foreach ($results as $result) { switch ($result->COLUMN_NAME) { case 'created_at': $column_names[$result->COLUMN_NAME] = '创建时间'; break; case 'updated_at': $column_names[$result->COLUMN_NAME] = '修改时间'; break; case 'deleted_at': $column_names[$result->COLUMN_NAME] = '删除时间'; break; default: $column_names[$result->COLUMN_NAME] = $result->COLUMN_COMMENT; break; } } return $column_names; }
/** * Execute the console command. * * @return mixed */ public function handle() { $count = 0; $pdo = DB::connection()->getPdo(); $query = "SELECT * FROM archivos_sat;"; $stmt = $pdo->prepare($query); $stmt->execute(); while ($row = $stmt->fetchObject()) { $count++; if ($count % 100 == 0) { $this->comment("arch sat: " . $count); } $archivo = ArchivoSat::find($row->id); $parser = new ParserCFID($archivo->file); $parser->parser(); $archivo->fecha = $parser->getFecha(); $archivo->save(); } $count = 0; $pdo = DB::connection()->getPdo(); $query = "SELECT * FROM archivos_empresa;"; $stmt = $pdo->prepare($query); $stmt->execute(); while ($row = $stmt->fetchObject()) { $count++; if ($count % 100 == 0) { $this->comment("arch emp: " . $count); } $archivo = ArchivoEmpresa::find($row->id); $parser = new ParserCFID($archivo->file); $parser->parser(); $archivo->fecha = $parser->getFecha(); $archivo->save(); } }
public function registerDi() { if ($this->registerDi) { return; } // Register service provider $this->container['logger'] = function ($c) { $arLogerConf = $c->settings['use_log'] ? $c->settings['register_log'] : []; $logger = new LoggerSystem(new Logger('slimcms_core'), $arLogerConf); //new Logger('slimcms_core'); $filename = $c->settings['log_filename'] ? $c->settings['log_filename'] : "app.log"; $handler = new StreamHandler(ROOT_PATH . "log/" . $filename); if ($c['settings']['log_system'] == 'db') { $handler = new MySQLHandler(DB::connection()->getPdo(), "logging"); if (DB::connection()->getDriverName() == 'sqlite') { $handler = new SqliteMonologHandler(DB::connection()->getPdo(), "logging"); } } if ($c['settings']['use_log']) { $logger->pushHandler($handler); } return $logger; }; $this->registerDi = true; }
public function getMmPoint(Request $request) { $key = request('key'); $mmpointM = DB::connection(DBUtils::getDBName())->table('mmpoint_table')->where('A', $key)->first(); // Log::info("lenth ".sizeof($mmtrendM)); return response()->json(['mmpointM' => json_encode($mmpointM)]); }
public function run() { DB::connection('devaudit')->table('Receipt_History')->delete(); /* * desc Receipt_History; +------------+---------------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+---------------------+------+-----+---------------------+----------------+ | activityID | bigint(20) unsigned | NO | PRI | NULL | auto_increment | | PO | bigint(20) | NO | | NULL | | | POD | bigint(20) | NO | | NULL | | | Article | bigint(20) | YES | | NULL | | | UPC | bigint(20) | YES | | NULL | | | Inventory | bigint(20) | YES | | NULL | | | Tote | bigint(20) | YES | | NULL | | | Cart | bigint(20) | YES | | NULL | | | Location | bigint(20) | YES | | NULL | | | User_Name | varchar(85) | NO | | NULL | | | created_at | timestamp | NO | | 0000-00-00 00:00:00 | | | updated_at | timestamp | NO | | 0000-00-00 00:00:00 | | | Activity | text | NO | | NULL | | +------------+---------------------+------+-----+---------------------+----------------+ 11 rows in set (0.01 sec) */ ReceiptHistory::create(['PO' => '6232063897', 'POD' => '6232063899', 'Article' => '6217093230', 'UPC' => '6217092826', 'Inventory' => '6231963444', 'Tote' => '6231978189', 'Cart' => '6216954640', 'Location' => '', 'User_Name' => 'pneal', 'Activity' => 'Received UPC into Tote - 2015-02-20 01:05:08, UPC# 63664347409, Tote# 52 0030 3099, (1 of 10)']); ReceiptHistory::create(['PO' => '6232063897', 'POD' => '6232063899', 'Article' => '6217093230', 'UPC' => '6217092826', 'Inventory' => '6231963444', 'Tote' => '6231978189', 'Cart' => '6216954640', 'Location' => '', 'User_Name' => 'pneal', 'Activity' => 'Received UPC into Tote - 2015-02-20 01:05:12, UPC# 63664347409, Tote# 52 0030 3099, (2 of 10)']); ReceiptHistory::create(['PO' => '6232063897', 'POD' => '6232063899', 'Article' => '6217093230', 'UPC' => '6217092826', 'Inventory' => '6231963444', 'Tote' => '6231978189', 'Cart' => '6216954640', 'Location' => '', 'User_Name' => 'pneal', 'Activity' => 'Received UPC into Tote - 2015-02-20 01:05:17, UPC# 63664347409, Tote# 52 0030 3099, (3 of 10)']); ReceiptHistory::create(['PO' => '6232063897', 'POD' => '6232063899', 'Article' => '6217093230', 'UPC' => '6217092826', 'Inventory' => '6231963444', 'Tote' => '6231978189', 'Cart' => '6216954640', 'Location' => '', 'User_Name' => 'pneal', 'Activity' => 'Received UPC into Tote - 2015-02-20 01:05:23, UPC# 63664347409, Tote# 52 0030 3099, (4 of 10)']); }
/** * Execute the console command. */ public function handle() { $file = base_path('resources') . '/new_name.txt'; $handle = fopen($file, 'r'); if (!$handle) { throw new FileNotFoundException($file); } while (($line = fgets($handle)) !== false) { $data = explode("\t", $line); if (count($data) != 2) { continue; } $newName = trim($data[1]); if (empty($newName)) { continue; } DB::update('update organizations set fullName=' . DB::connection()->getPdo()->quote($newName) . ' where edrpou=' . DB::connection()->getPdo()->quote($data[0]) . ' limit 1'); var_dump(1); // if(++$j >= 2000) { // $values = implode(', ', array_map(function($v){ // foreach($v as &$vv) // $vv = DB::connection()->getPdo()->quote($vv); // return '('. implode(',', $v) .')'; // }, $rows)); // // DB::insert('insert ignore into `fio` (`name`, `nameRU`) values '. $values .' ON DUPLICATE KEY UPDATE c=c+1'); // $j = 0; // $rows = []; // } } fclose($handle); }
public function __construct() { $this->schema = DB::connection()->getSchemaBuilder(); $this->schema->blueprintResolver(function ($table, $callback) { return new Blueprint($table, $callback); }); }
public function diagnosed(Request $request) { $this->validate($request, ["mrId" => "required", "bldp" => "required", "docId" => "required"]); DB::connection("centraldb")->table('MR' . $_POST["patId"])->where('id', $_POST["mrId"])->update(array('flag' => 1, "data" => $_POST["bldp"])); General::addToQ($_POST["docId"], $_POST["patId"]); return redirect("diag"); }
/** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { $new_id = User::all()->count() > 0 ? User::orderBy('id', 'desc')->first()->id + 1 : 2400; DB::connection('member')->table('tb_user')->insert(['mid' => $data['name'], 'password' => $data['password'], 'pwd' => Hash::make($data['password']), 'idnum' => $new_id]); DB::connection('account')->table('accounts')->insert(['id' => $new_id, 'username' => $data['name'], 'password' => $data['password']]); return User::create(['id' => $new_id, 'username' => $data['name'], 'password' => Hash::make($data['password']), 'role' => 'member']); }
/** * Bootstrap the application services. * * @return void */ public function boot() { view()->composer(['front.header', 'admin.header'], function ($view) { $languages = []; $folders = File::directories(base_path('resources/lang/')); foreach ($folders as $folder) { $languages[] = str_replace('\\', '', last(explode('/', $folder))); } $view->with('languages', $languages); }); view()->composer('front.header', function ($view) { $apps = Application::all(); $view->with('apps', $apps); }); view()->composer('admin.news.form', function ($view) { $categories = ['update' => trans('news.category.update'), 'maintenance' => trans('news.category.maintenance'), 'event' => trans('news.category.event'), 'contest' => trans('news.category.contest'), 'other' => trans('news.category.other')]; $view->with('categories', $categories); }); view()->composer('front.widgets', function ($view) { $client_status = @fsockopen(settings('server_ip', '127.0.0.1'), 6543, $errCode, $errStr, 1) ? TRUE : FALSE; $worlds = DB::connection('account')->table('worlds')->get(); $view->with('client_status', $client_status)->with('worlds', $worlds); }); view()->composer('admin.donate.settings', function ($view) { $view->with('currencies', trans('donate.currency')); }); }
/** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { // Check that the schedules table exists. This // could cause a fatal error if the app is // still being setup or the db has not yet // been configured. This is a relatively ugly // hack as this schedule() method is core to // the framework. try { DB::connection(); if (!Schema::hasTable('schedules')) { throw new Exception('Schema schedules does not exist'); } } catch (Exception $e) { return; } // Load the schedule from the database foreach (DbSchedule::all() as $job) { $command = $schedule->command($job['command'])->cron($job['expression']); // Check if overlapping is allowed if (!$job['allow_overlap']) { $command = $command->withoutOverlapping(); } // Check if maintenance mode is allowed if ($job['allow_maintenance']) { $command = $command->evenInMaintenanceMode(); } if ($job['ping_before']) { $command = $command->pingBefore($job['ping_before']); } if ($job['ping_after']) { $command->thenPing($job['ping_after']); } } }
public function run() { if (DB::connection()->getDriverName() == 'mysql') { DB::statement('SET FOREIGN_KEY_CHECKS=0;'); } if (DB::connection()->getDriverName() == 'mysql') { DB::table(config('access.assigned_roles_table'))->truncate(); } elseif (DB::connection()->getDriverName() == 'sqlite') { DB::statement('DELETE FROM ' . config('access.assigned_roles_table')); } else { //For PostgreSQL or anything else DB::statement('TRUNCATE TABLE ' . config('access.assigned_roles_table') . ' CASCADE'); } //Attach admin role to admin user $user_model = config('auth.providers.users.model'); $user_model = new $user_model(); $user_model::first()->attachRole(1); //Attach executive role to executive user $user_model = config('auth.providers.users.model'); $user_model = new $user_model(); $user_model::find(2)->attachRole(2); //Attach user role to general user $user_model = config('auth.providers.users.model'); $user_model = new $user_model(); $user_model::find(3)->attachRole(3); if (DB::connection()->getDriverName() == 'mysql') { DB::statement('SET FOREIGN_KEY_CHECKS=1;'); } }
/** * Display a listing of the resource. * * @return Response */ public function index() { DB::connection()->enableQueryLog(); $filter = array_replace(['type' => 'all', 'day' => 'any', 'sizes' => [], 'specs' => [], 'via' => ['Hamburg', '', '', 'Berlin'], 'sort' => 'price desc'], Input::get('filter', [])); $shipments = Shipment::ofType($filter['type'])->via($filter['via'])->shipsOn($filter['day'])->onlySizes($filter['sizes'])->withoutSpecs('specs', $filter['specs'])->get(); $shipments = $this->sortShipments($shipments, $filter['sort']); return view('shipments.index')->with('shipments', $shipments)->with('filter', $filter)->with('sizes', Size::all())->with('specs', Spec::all()); }
public function tearDown() { DB::connection()->rollBack(); //rollback the transaction so the test case can be rerun without duplicate key exceptions DB::connection()->setPdo(null); //close the pdo connection to `avoid too many connections` errors parent::tearDown(); }
public function mysql() { try { return (bool) (!is_null(DB::connection()->getDatabaseName())); } catch (\Exception $e) { return false; } }
/** * Execute the console command. * * @return mixed */ public function fire() { //register log in DB $dateBegin = new \DateTime(); $activity = Activity::concept(ConstDb::LOAD_CRL)->first(); if ($activity) { $activity->date_begin = $dateBegin->format('Y-m-d H:i:s'); $activity->save(); } else { Activity::create(['concept' => ConstDb::LOAD_CRL, 'date_begin' => $dateBegin->format('Y-m-d H:i:s')]); } //end log $this->info('Begin: ' . date('H:i:s')); $result = DB::connection('mysql_crl')->select($this->getQuery(true)); $rows = $result[0]->total; $this->info("Total de filas: {$rows}"); $begin = 0; $block = 10000; $countBlock = 1; $fCsv = storage_path('app/crl.csv'); if (file_exists($fCsv)) { unlink($fCsv); } $fp = fopen($fCsv, 'w'); fputs($fp, "organization, from, year, quarter, month, total \n"); while ($rows > $begin) { $result = DB::connection('mysql_crl')->select($this->getQuery(false, $begin, $block)); foreach ($result as $key => $value) { $array = json_decode(json_encode($value), true); $replace = ["\n", ',', ' ']; $replaceTo = ["", ';', ' ']; foreach ($array as $key => $value) { $array[$key] = str_replace($replace, $replaceTo, $value); } fputs($fp, implode($array, ',') . "\n"); } $this->info("End block {$countBlock}: " . date('H:i:s')); $begin += $block; $countBlock++; } fclose($fp); $this->info('End export CSV: ' . date('H:i:s')); Schema::drop('crl'); $db = env('MONGO_DATABASE'); $command = "mongoimport -d {$db} -c crl --type csv --file {$fCsv} --headerline"; shell_exec($command); //register log in DB $dateEnd = new \DateTime(); $activity = Activity::concept(ConstDb::LOAD_CRL)->first(); if ($activity) { $activity->date_end = $dateEnd->format('Y-m-d H:i:s'); $activity->save(); } else { Activity::create(['concept' => ConstDb::LOAD_CRL, 'date_end' => $dateEnd->format('Y-m-d H:i:s')]); } //end log $this->info('End: ' . $dateEnd->format('H:i:s')); }
/** * Create a new command instance. * @return void */ public function __construct() { try { $this->db = DB::connection('friends_wordpress'); } catch (\InvalidArgumentException $e) { Log::info('Missing configuration for wordpress migration'); } parent::__construct(); }
/** * @param array $values * @return string */ private function _implodeValues(array $values) { return implode(', ', array_map(function ($v) { foreach ($v as &$vv) { $vv = DB::connection()->getPdo()->quote($vv); } return '(' . implode(',', $v) . ')'; }, $values)); }
/** * 返回所有文章 */ function GetAllPost(Request $request) { DB::connection()->enableQueryLog(); $postSrv = new Post(); $res = $postSrv->GetAllPost($request->all()); $res['success'] = $res['data'] ? true : false; $res['sql'] = DB::getQueryLog(); return json_encode($res, JSON_UNESCAPED_UNICODE); }
public function getLog(Request $request) { if ($request->user()->cannot('server_whitelist_log_show')) { abort('403', 'You do not have the required permission'); } DB::connection('server')->setFetchMode(PDO::FETCH_ASSOC); $logs = DB::connection('server')->table('whitelist_log')->get(); return view('server.whitelist.log', ['logs' => $logs]); }
function __construct($connection_name = '') { if (self::$pdo == null) { self::$pdo = DB::connection($connection_name)->getPdo(); self::$pdo->exec('SET NAMES UTF8'); //follow .env $this->NeedDumpInfo(env('APP_DEBUG')); } }
public function connect($site_id) { try { return $this->DB_site = DB::connection($site_id . '_production'); } catch (\PDOException $e) { echo "No database [{$site_id}] connection"; exit; } }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { $input = Request::all(); Batch::create($input); DB::connection()->enableQueryLog(); \DB::enableQueryLog(); dd($input); // }
public function update_wialon_cars() { $wia_cars = $this->wialon->get_units(); DB::connection($this->city->db)->table('wialon_cars')->truncate(); foreach ($wia_cars as $v) { $gn = substr($v->nm, 0, 5); $insert_data = ["wia_id" => $v->id, 'gn' => $gn, 'last_message' => isset($v->pos) ? $v->pos->t : 0, 'pos_x' => isset($v->pos) ? $v->pos->x : 0, 'pos_y' => isset($v->pos) ? $v->pos->y : 0, 'uptime' => time()]; DB::connection($this->city->db)->table('wialon_cars')->insert($insert_data); } }