|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace UKTowns\Console; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Console\Command; |
|
6
|
|
|
use Illuminate\Database\Schema\Blueprint; |
|
7
|
|
|
use Illuminate\Support\Facades\DB; |
|
8
|
|
|
use Illuminate\Support\Facades\Schema; |
|
9
|
|
|
use UKTowns\Models\GeoPostcode; |
|
10
|
|
|
|
|
11
|
|
|
class ImportPostcodesToDatabase extends Command |
|
12
|
|
|
{ |
|
13
|
|
|
protected $signature = 'uk-towns:postcodes:import |
|
14
|
|
|
{--no-truncate : Flag to prevent truncate table before upload} |
|
15
|
|
|
'; |
|
16
|
|
|
|
|
17
|
|
|
protected $description = 'Import postcodes table to database.'; |
|
18
|
|
|
|
|
19
|
2 |
|
public function handle(): int |
|
20
|
|
|
{ |
|
21
|
2 |
|
$tableName = (new GeoPostcode())->getTable(); |
|
22
|
|
|
|
|
23
|
2 |
|
if (!Schema::hasTable($tableName)) { |
|
24
|
1 |
|
Schema::create($tableName, function (Blueprint $table) { |
|
25
|
1 |
|
$table->string('postcode', 50)->primary(); |
|
26
|
1 |
|
$table->string('postcode_compact', 50)->index(); |
|
27
|
1 |
|
$table->string('description', 255); |
|
28
|
1 |
|
$table->string('place', 200)->nullable(); |
|
29
|
1 |
|
$table->string('country', 200)->nullable(); |
|
30
|
1 |
|
$table->decimal('latitude', 10, 7)->index(); |
|
31
|
1 |
|
$table->decimal('longitude', 10, 7)->index(); |
|
32
|
1 |
|
$table->timestamps(); |
|
33
|
|
|
}); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
2 |
|
if (!$this->option('no-truncate')) { |
|
37
|
2 |
|
DB::table($tableName)->truncate(); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
2 |
|
for ($i = 0; $i <= 3; $i++) { |
|
41
|
2 |
|
$filePath = __DIR__."/../../storage/uk-postcodes-{$i}.csv"; |
|
42
|
2 |
|
$sqlScript = "LOAD DATA LOCAL INFILE '{$filePath}' |
|
43
|
|
|
INTO TABLE `{$tableName}` |
|
44
|
2 |
|
CHARACTER SET '{$this->character()}' |
|
45
|
|
|
FIELDS TERMINATED BY ',' |
|
46
|
|
|
OPTIONALLY ENCLOSED BY '\"' |
|
47
|
|
|
LINES TERMINATED BY '\n' |
|
48
|
|
|
IGNORE 1 LINES |
|
49
|
|
|
( |
|
50
|
|
|
postcode, |
|
51
|
|
|
postcode_compact, |
|
52
|
|
|
description, |
|
53
|
|
|
place, |
|
54
|
|
|
country, |
|
55
|
|
|
latitude, |
|
56
|
|
|
longitude, |
|
57
|
|
|
created_at, |
|
58
|
|
|
updated_at |
|
59
|
|
|
)"; |
|
60
|
|
|
|
|
61
|
2 |
|
DB::statement('SET FOREIGN_KEY_CHECKS=0;'); |
|
62
|
2 |
|
DB::statement(trim($sqlScript)); |
|
63
|
2 |
|
DB::statement('SET FOREIGN_KEY_CHECKS=1;'); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
2 |
|
return 0; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
2 |
|
protected function character(): string |
|
70
|
|
|
{ |
|
71
|
2 |
|
return 'utf8mb4'; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|