ExportCreateDb.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\Storage;
  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(\App\Tools\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. $sqlPath = database_path('export/'.$sqlFile);
  46. $exportDir = storage_path('app/public/export/offline');
  47. $exportFile = $exportDir.'/'.$dbFile.'-'.date("Y-m-d").'.db3';
  48. $file = fopen($exportFile,'w');
  49. fclose($file);
  50. $dbh = new \PDO('sqlite:'.$exportFile, "", "", array(\PDO::ATTR_PERSISTENT => true));
  51. $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
  52. //建立数据库
  53. $_sql = file_get_contents($sqlPath);
  54. $_arr = explode(';', $_sql);
  55. //执行sql语句
  56. foreach ($_arr as $_value) {
  57. $dbh->query($_value . ';');
  58. }
  59. Log::debug('task export offline create-db finished');
  60. }
  61. }