ExportCreateDb.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Tools\Tools;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\Log;
  6. class ExportCreateDb extends Command
  7. {
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'export:create.db';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = 'Command description';
  20. /**
  21. * Create a new command instance.
  22. *
  23. * @return void
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. }
  29. /**
  30. * Execute the console command.
  31. *
  32. * @return int
  33. */
  34. public function handle()
  35. {
  36. Log::debug('task export offline create-db start');
  37. if (Tools::isStop()) {
  38. return 0;
  39. }
  40. $this->create('sentence.sql', 'wikipali-offline');
  41. $this->create('sentence.sql', 'wikipali-offline-index');
  42. return 0;
  43. }
  44. private function create($sqlFile, $dbFile)
  45. {
  46. $sqlPath = database_path('export/'.$sqlFile);
  47. $exportDir = storage_path('app/public/export/offline');
  48. $exportFile = $exportDir.'/'.$dbFile.'-'.date('Y-m-d').'.db3';
  49. $file = fopen($exportFile, 'w');
  50. fclose($file);
  51. $dbh = new \PDO('sqlite:'.$exportFile, '', '', [\PDO::ATTR_PERSISTENT => true]);
  52. $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
  53. // 建立数据库
  54. $_sql = file_get_contents($sqlPath);
  55. $_arr = explode(';', $_sql);
  56. // 执行sql语句
  57. foreach ($_arr as $_value) {
  58. $dbh->query($_value.';');
  59. }
  60. Log::debug('task export offline create-db finished');
  61. }
  62. }