-
Notifications
You must be signed in to change notification settings - Fork 38
/
AlternateName.php
555 lines (459 loc) · 25.2 KB
/
AlternateName.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
<?php
namespace MichaelDrennen\Geonames\Console;
use Carbon\Carbon;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use MichaelDrennen\Geonames\Models\GeoSetting;
use MichaelDrennen\Geonames\Models\Log;
use MichaelDrennen\LocalFile\LocalFile;
use MichaelDrennen\Geonames\Models\AlternateNamesWorking;
/**
* Class AlternateName
*
* @package MichaelDrennen\Geonames\Console
*/
class AlternateName extends AbstractCommand {
use GeonamesConsoleTrait;
const LINES_PER_SPLIT_FILE = 5000;
/**
* @var string The name and signature of the console command.
*/
protected $signature = 'geonames:alternate-name
{--connection= : If you want to specify the name of the database connection you want used.}
{--test : If you want to test the command on a small countries data set.}
{--country=* : Add the 2 character code for each country. Add additional countries with additional "--country=" options on the command line.} ';
/**
* @var string The console command description.
*/
protected $description = "Populate the alternate_names table.";
/**
*
*/
const REMOTE_FILE_NAME_FOR_ALL = 'alternateNames.zip';
/**
*
*/
const LOCAL_ALTERNATE_NAMES_FILE_NAME_FOR_ALL = 'alternateNames.txt';
/**
* The name of our alternate names table in our database. Using constants here, so I don't need
* to worry about typos in my code. My IDE will warn me if I'm sloppy.
*/
const TABLE = 'geonames_alternate_names';
/**
* The name of our temporary/working table in our database.
*/
const TABLE_WORKING = 'geonames_alternate_names_working';
/**
* Initialize constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Execute the console command. The zip file this command downloads has two files in it. The alternate names, and
* iso language codes file. The iso language codes file is available as a separate download, so for simplicity's
* sake I handle the iso language code download and insertion in another console command.
*
* @return bool
* @throws Exception
*/
public function handle() {
ini_set( 'memory_limit', -1 );
$this->startTimer();
//$this->connectionName = $this->option( 'connection' );
$this->setDatabaseConnectionName();
if ( $this->option( 'test' ) ):
$countries = [ 'BS','YU','UZ' ];
else:
$countries = $this->option( 'country' );
endif;
try {
$this->setDatabaseConnectionName();
$this->info( "The database connection name was set to: " . $this->connectionName );
$this->comment( "Testing database connection..." );
$this->checkDatabase();
$this->info( "Confirmed database connection set up correctly." );
} catch ( \Exception $exception ) {
$this->error( $exception->getMessage() );
$this->stopTimer();
return FALSE;
}
try {
GeoSetting::init(
$countries,
GeoSetting::DEFAULT_LANGUAGES,
GeoSetting::DEFAULT_STORAGE_SUBDIR,
$this->connectionName );
} catch ( \Exception $exception ) {
Log::error( NULL, "Unable to initialize the GeoSetting record.", '', $this->connectionName );
$this->stopTimer();
return FALSE;
}
$this->initTable();
$urlsToAlternateNamesZipFiles = $this->getAlternateNameDownloadLinks( $countries );
$absoluteLocalFilePathsOfAlternateNamesZipFiles = [];
foreach ( $urlsToAlternateNamesZipFiles as $countryCode => $urlsToAlternateNamesZipFile ) {
try {
$absoluteLocalFilePathsOfAlternateNamesZipFiles[ $countryCode ] = $this->downloadFile( $this,
$urlsToAlternateNamesZipFile,
$this->connectionName );
} catch ( \Exception $e ) {
$this->error( $e->getMessage() );
Log::error( $urlsToAlternateNamesZipFiles, $e->getMessage(), 'remote', $this->connectionName );
return FALSE;
}
}
$this->comment( "Done downloading alternate zip files." );
foreach ( $absoluteLocalFilePathsOfAlternateNamesZipFiles as $countryCode => $absoluteLocalFilePathOfAlternateNamesZipFile ) {
try {
$this->unzip( $absoluteLocalFilePathOfAlternateNamesZipFile, $this->connectionName );
$this->comment( "Unzipped " . $absoluteLocalFilePathOfAlternateNamesZipFile );
} catch ( \Exception $e ) {
$this->error( $e->getMessage() );
Log::error( $absoluteLocalFilePathOfAlternateNamesZipFile, $e->getMessage(), 'local',
$this->connectionName );
return FALSE;
}
$absoluteLocalFilePathOfAlternateNamesFile = $this->getLocalAbsolutePathToAlternateNamesTextFile( $countryCode );
if ( ! file_exists( $absoluteLocalFilePathOfAlternateNamesFile ) ) {
throw new Exception( "The unzipped file could not be found. We were looking for: " . $absoluteLocalFilePathOfAlternateNamesFile );
}
//$this->insertAlternateNamesWithLoadDataInfile( $absoluteLocalFilePathOfAlternateNamesFile );
$this->insertAlternateNamesWithEloquent( $absoluteLocalFilePathOfAlternateNamesFile );
//$this->insertAlternateNamesWithEloquentMassInsert( $absoluteLocalFilePathOfAlternateNamesFile );
//$this->insertAlternateNamesWithLoadDataInfileFromRecreatedFile( $absoluteLocalFilePathOfAlternateNamesFile );
}
$this->finalizeTable();
$this->info( "alternate_names data was downloaded and inserted in " . $this->getRunTime() . " seconds." );
}
/**
* @param array $countryCodes The two character country code, if specified by the user.
*
* @return array The absolute paths to the remote alternate names zip files.
*/
protected function getAlternateNameDownloadLinks( array $countryCodes = [] ): array {
if ( empty( $countryCodes ) ):
return [ '*' => self::$url . self::REMOTE_FILE_NAME_FOR_ALL ];
endif;
$alternateNameDownloadLinks = [];
foreach ( $countryCodes as $i => $countryCode ) {
$alternateNameDownloadLinks[ $countryCode ] = self::$url . 'alternatenames/' . strtoupper( $countryCode ) . '.zip';
}
return $alternateNameDownloadLinks;
}
/**
* This function is used in debugging only. The main block of code has no need for this function, since the
* downloadFile() function returns this exact path as it's return value. The alternate names file takes a while
* to download on my slow connection, so I save a copy of it for testing, and use this function to point to it.
*
* @return string The absolute local path to the downloaded zip file.
* @throws \Exception
*/
protected function getLocalAbsolutePathToAlternateNamesZipFile(): string {
return GeoSetting::getAbsoluteLocalStoragePath( $this->connectionName ) . DIRECTORY_SEPARATOR . self::REMOTE_FILE_NAME_FOR_ALL;
}
/**
* @param string $countryCode The two character country code that a user can optionally pass in.
*
* @return string
* @throws \Exception
*/
protected function getLocalAbsolutePathToAlternateNamesTextFile( string $countryCode = NULL ): string {
if ( '*' == $countryCode || is_null( $countryCode ) ):
return GeoSetting::getAbsoluteLocalStoragePath( $this->connectionName ) . DIRECTORY_SEPARATOR . self::LOCAL_ALTERNATE_NAMES_FILE_NAME_FOR_ALL;
endif;
return GeoSetting::getAbsoluteLocalStoragePath( $this->connectionName ) . DIRECTORY_SEPARATOR . strtoupper( $countryCode ) . '.txt';
}
protected function initTable() {
$this->makeWorkingTable(self::TABLE, self::TABLE_WORKING);
// Schema::connection( $this->connectionName )->dropIfExists( self::TABLE_WORKING );
// DB::connection( $this->connectionName )
// ->statement( 'CREATE TABLE ' . self::TABLE_WORKING . ' LIKE ' . self::TABLE . ';' );
$this->disableKeys( self::TABLE_WORKING );
}
protected function finalizeTable() {
$this->enableKeys( self::TABLE_WORKING );
Schema::connection( $this->connectionName )->dropIfExists( self::TABLE );
Schema::connection( $this->connectionName )->rename( self::TABLE_WORKING, self::TABLE );
}
/**
* @param $localFilePath
*
* @returns int The total number of rows inserted.
* @throws \Exception
*/
protected function insertAlternateNamesWithLoadDataInfile( $localFilePath ): int {
$totalRowsInserted = 0;
try {
$localFileSplitPaths = LocalFile::split( $localFilePath, self::LINES_PER_SPLIT_FILE, 'split_', NULL );
$numSplitFiles = count( $localFileSplitPaths );
} catch ( \Exception $exception ) {
throw $exception;
}
$charset = config( "database.connections.{$this->connectionName}.charset", 'utf8mb4' );
foreach ( $localFileSplitPaths as $i => $localFileSplitPath ):
// Windows patch
$localFileSplitPath = $this->fixDirectorySeparatorForWindows( $localFileSplitPath );
$query = "LOAD DATA LOCAL INFILE '" . $localFileSplitPath . "'
INTO TABLE " . self::TABLE_WORKING . " CHARACTER SET '{$charset}'
( alternateNameId,
geonameid,
isolanguage,
alternate_name,
isPreferredName,
isShortName,
isColloquial,
isHistoric,
@created_at,
@updated_at)
SET created_at=NOW(),updated_at=null
";
$this->line( "Running the LOAD DATA INFILE query. This could take a good long while." );
/**
* @link http://php.net/manual/en/pdo.exec.php
* PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued.
* If no rows were affected, PDO::exec() returns 0.
*/
try {
$rowsInserted = DB::connection( $this->connectionName )->getpdo()->exec( $query );
} catch ( \Exception $exception ) {
throw new \Exception( "Unable to execute the load data infile query. " . print_r( DB::connection( $this->connectionName )
->getpdo()
->errorInfo(),
TRUE ) . " QUERY: " . $query );
}
if ( FALSE === $rowsInserted ) {
Log::error( '', "Unable to load data infile for alternate names.", 'database', $this->connectionName );
throw new \Exception( "Unable to execute the load data infile query. " . print_r( DB::connection( $this->connectionName )
->getpdo()
->errorInfo(),
TRUE ) );
}
$this->info( "Inserted file " . ( $i + 1 ) . " of " . $numSplitFiles );
$totalRowsInserted += $rowsInserted;
endforeach;
return $totalRowsInserted;
}
protected function insertAlternateNamesWithLoadDataInfileFromRecreatedFile( $localFilePath ): int {
try {
$this->comment( "Inserting alternate names using insertAlternateNamesWithLoadDataInfileFromRecreatedFile()" );
$totalLinesInOriginalFile = LocalFile::lineCount( $localFilePath );
$this->comment( "Splitting " . $localFilePath );
$localFileSplitPaths = LocalFile::split( $localFilePath, self::LINES_PER_SPLIT_FILE, 'split_', NULL );
$numSplitFiles = count( $localFileSplitPaths );
$this->comment( "$localFilePath was split into $numSplitFiles files." );
} catch ( \Exception $exception ) {
throw $exception;
}
$geonamesBar = $this->output->createProgressBar( $totalLinesInOriginalFile );
$geonamesBar->setFormat( "Recreating %message% %current%/%max% [%bar%] %percent:3s%%\n" );
$totalRowsRecreated = 0;
$pathToRecreatedFile = './recreatedFile.txt';
$recreatedFileHandle = fopen( $pathToRecreatedFile, 'w' );
foreach ( $localFileSplitPaths as $i => $localFileSplitPath ):
$geonamesBar->setMessage( "file #" . ( $i + 1 ) . " of " . $numSplitFiles );
$rows = file( $localFileSplitPath );
//$numRowsInSplitFile = count( $rows );
foreach ( $rows as $j => $row ):
$recreatedFields = [];
$fields = explode( "\t", $row );
$fields = array_map( 'trim', $fields );
$recreatedFields[] = $fields[ 0 ];
$recreatedFields[] = $fields[ 1 ];
$recreatedFields[] = empty( $fields[ 2 ] ) ? '' : $fields[ 2 ];
$recreatedFields[] = empty( $fields[ 3 ] ) ? '' : $fields[ 3 ];
$recreatedFields[] = empty( $fields[ 4 ] ) ? FALSE : $fields[ 4 ];
$recreatedFields[] = empty( $fields[ 5 ] ) ? FALSE : $fields[ 5 ];
$recreatedFields[] = empty( $fields[ 6 ] ) ? FALSE : $fields[ 6 ];
$recreatedFields[] = empty( $fields[ 7 ] ) ? FALSE : $fields[ 7 ];
fwrite( $recreatedFileHandle, implode( "\t", $recreatedFields ) . "\n" );
$totalRowsRecreated++;
$geonamesBar->advance();
endforeach;
endforeach;
fclose( $recreatedFileHandle );
$geonamesBar->finish();
$this->comment( "Running LOAD DATA INFILE." );
// Windows patch
$pathToRecreatedFile = $this->fixDirectorySeparatorForWindows( $pathToRecreatedFile );
$charset = config( "database.connections.{$this->connectionName}.charset", 'utf8mb4' );
$query = "LOAD DATA LOCAL INFILE '" . $pathToRecreatedFile . "'
INTO TABLE " . self::TABLE_WORKING . " CHARACTER SET '{$charset}'
( alternateNameId,
geonameid,
isolanguage,
alternate_name,
isPreferredName,
isShortName,
isColloquial,
isHistoric,
@created_at,
@updated_at)
SET created_at=NOW(),updated_at=null
";
$this->line( "Running the LOAD DATA INFILE query. This could take a good long while." );
/**
* @link http://php.net/manual/en/pdo.exec.php
* PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued.
* If no rows were affected, PDO::exec() returns 0.
*/
try {
$rowsInserted = DB::connection( $this->connectionName )->getpdo()->exec( $query );
} catch ( \Exception $exception ) {
throw new \Exception( "Unable to execute the load data infile query. " . print_r( DB::connection( $this->connectionName )
->getpdo()
->errorInfo(),
TRUE ) . " QUERY: " . $query );
}
if ( FALSE === $rowsInserted ) {
Log::error( '', "Unable to load data infile for alternate names.", 'database', $this->connectionName );
throw new \Exception( "Unable to execute the load data infile query. " . print_r( DB::connection( $this->connectionName )
->getpdo()
->errorInfo(), TRUE ) );
}
unlink( $pathToRecreatedFile );
return $totalRowsRecreated;
}
/**
* I have been getting a UTF-8 error when
*
* @param $localFilePath
*
* @return int
* @throws \Exception
*/
protected function insertAlternateNamesWithEloquent( $localFilePath ): int {
//DB::enableQueryLog();
$numLines = LocalFile::lineCount( $localFilePath );
$this->disableKeys( self::TABLE );
try {
$this->comment( "Splitting " . $localFilePath );
$localFileSplitPaths = LocalFile::split( $localFilePath, self::LINES_PER_SPLIT_FILE, 'split_', NULL );
$numSplitFiles = count( $localFileSplitPaths );
$this->comment( "I split $localFilePath into $numSplitFiles split files." );
} catch ( \Exception $exception ) {
throw $exception;
}
$totalRowsInserted = 0;
foreach ( $localFileSplitPaths as $i => $localFileSplitPath ):
$rows = file( $localFileSplitPath );
$numRowsInSplitFile = count( $rows );
$this->comment( "Split file #" . ( $i + 1 ) . " of " . $numSplitFiles . " has $numRowsInSplitFile rows." );
$geonamesBar = $this->output->createProgressBar( $numRowsInSplitFile );
$geonamesBar->setFormat( "Inserting %message% %current%/%max% [%bar%] %percent:3s%%\n" );
$geonamesBar->setMessage( 'alternate names' );
/**
* alternateNameId : the id of this alternate name, int
* geonameid : geonameId referring to id in table 'geoname', int
* isolanguage : iso 639 language code 2- or 3-characters; 4-characters 'post' for postal codes and 'iata','icao' and faac for airport codes, fr_1793 for French Revolution names, abbr for abbreviation, link to a website (mostly to wikipedia), wkdt for the wikidataid, varchar(7)
* alternate name : alternate name or name variant, varchar(400)
* isPreferredName : '1', if this alternate name is an official/preferred name
* isShortName : '1', if this is a short name like 'California' for 'State of California'
* isColloquial : '1', if this alternate name is a colloquial or slang term. Example: 'Big Apple' for 'New York'.
* isHistoric : '1', if this alternate name is historic and was used in the past. Example 'Bombay' for 'Mumbai'.
*/
foreach ( $rows as $j => $row ) {
$fields = explode( "\t", $row );
$fields = array_map( 'trim', $fields );
$alternateNameId = $fields[ 0 ];
$geonameid = $fields[ 1 ];
$isolanguage = empty( $fields[ 2 ] ) ? '' : $fields[ 2 ];
$alternate_name = empty( $fields[ 3 ] ) ? '' : $fields[ 3 ];
$isPreferredName = empty( $fields[ 4 ] ) ? FALSE : $fields[ 4 ];
$isShortName = empty( $fields[ 5 ] ) ? FALSE : $fields[ 5 ];
$isColloquial = empty( $fields[ 6 ] ) ? FALSE : $fields[ 6 ];
$isHistoric = empty( $fields[ 7 ] ) ? FALSE : $fields[ 7 ];
$alternateName = \MichaelDrennen\Geonames\Models\AlternateNamesWorking::on( $this->connectionName )
->firstOrCreate(
[ 'alternateNameId' => $alternateNameId ],
[
'geonameid' => $geonameid,
'isolanguage' => $isolanguage,
'alternate_name' => $alternate_name,
'isPreferredName' => $isPreferredName,
'isShortName' => $isShortName,
'isColloquial' => $isColloquial,
'isHistoric' => $isHistoric,
]
);
$geonamesBar->advance();
$totalRowsInserted++;
}
$geonamesBar->finish();
endforeach;
$this->enableKeys( self::TABLE );
return $totalRowsInserted;
}
/**
* I have been getting a UTF-8 error when
*
* @param $localFilePath
*
* @return int
* @throws \Exception
*/
protected function insertAlternateNamesWithEloquentMassInsert( $localFilePath ): int {
$numLines = LocalFile::lineCount( $localFilePath );
$this->disableKeys( self::TABLE );
try {
$this->comment( "Splitting " . $localFilePath );
$localFileSplitPaths = LocalFile::split( $localFilePath, self::LINES_PER_SPLIT_FILE, 'split_', NULL );
$numSplitFiles = count( $localFileSplitPaths );
$this->comment( "I split $localFilePath into $numSplitFiles split files." );
} catch ( \Exception $exception ) {
throw $exception;
}
$totalRowsInserted = 0;
foreach ( $localFileSplitPaths as $i => $localFileSplitPath ):
$rows = file( $localFileSplitPath );
$numRowsInSplitFile = count( $rows );
$this->comment( "Split file #" . ( $i + 1 ) . " of " . $numSplitFiles . " has $numRowsInSplitFile rows." );
$geonamesBar = $this->output->createProgressBar( $numRowsInSplitFile );
$geonamesBar->setFormat( "Inserting %message% %current%/%max% [%bar%] %percent:3s%%\n" );
$geonamesBar->setMessage( 'alternate names' );
$splitRowsToInsert = [];
/**
* alternateNameId : the id of this alternate name, int
* geonameid : geonameId referring to id in table 'geoname', int
* isolanguage : iso 639 language code 2- or 3-characters; 4-characters 'post' for postal codes and 'iata','icao' and faac for airport codes, fr_1793 for French Revolution names, abbr for abbreviation, link to a website (mostly to wikipedia), wkdt for the wikidataid, varchar(7)
* alternate name : alternate name or name variant, varchar(400)
* isPreferredName : '1', if this alternate name is an official/preferred name
* isShortName : '1', if this is a short name like 'California' for 'State of California'
* isColloquial : '1', if this alternate name is a colloquial or slang term. Example: 'Big Apple' for 'New York'.
* isHistoric : '1', if this alternate name is historic and was used in the past. Example 'Bombay' for 'Mumbai'.
*/
foreach ( $rows as $j => $row ) {
$fields = explode( "\t", $row );
//$fields = array_map( 'trim', $fields );
$alternateNameId = $fields[ 0 ];
$geonameid = $fields[ 1 ];
$isolanguage = empty( $fields[ 2 ] ) ? '' : $fields[ 2 ];
$alternate_name = empty( $fields[ 3 ] ) ? '' : $fields[ 3 ];
$isPreferredName = empty( $fields[ 4 ] ) ? FALSE : $fields[ 4 ];
$isShortName = empty( $fields[ 5 ] ) ? FALSE : $fields[ 5 ];
$isColloquial = empty( $fields[ 6 ] ) ? FALSE : $fields[ 6 ];
$isHistoric = empty( $fields[ 7 ] ) ? FALSE : $fields[ 7 ];
$splitRowsToInsert[] = [
'alternateNameId' => $alternateNameId,
'geonameid' => $geonameid,
'isolanguage' => $isolanguage,
'alternate_name' => $alternate_name,
'isPreferredName' => $isPreferredName,
'isShortName' => $isShortName,
'isColloquial' => $isColloquial,
'isHistoric' => $isHistoric,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
];
$geonamesBar->advance();
$totalRowsInserted++;
}
$this->comment( "Inserting $numRowsInSplitFile rows from split file..." );
AlternateNamesWorking::on( $this->connectionName )->insert( $splitRowsToInsert );
$geonamesBar->finish();
endforeach;
return $totalRowsInserted;
}
}