ejaculated_dateの重複エラーをcatch

This commit is contained in:
shibafu 2020-05-21 23:13:39 +09:00
parent fa4827f382
commit 8681c328d0
2 changed files with 34 additions and 3 deletions

View File

@ -8,9 +8,11 @@ use App\Rules\CsvDateTime;
use App\Tag; use App\Tag;
use App\User; use App\User;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;
use League\Csv\Reader; use League\Csv\Reader;
use Throwable;
class CheckinCsvImporter class CheckinCsvImporter
{ {
@ -78,10 +80,24 @@ class CheckinCsvImporter
continue; continue;
} }
DB::beginTransaction();
try {
$ejaculation->save(); $ejaculation->save();
if (!empty($tags)) { if (!empty($tags)) {
$ejaculation->tags()->sync(collect($tags)->pluck('id')); $ejaculation->tags()->sync(collect($tags)->pluck('id'));
} }
DB::commit();
} catch (QueryException $e) {
DB::rollBack();
if ($e->errorInfo[0] === '23505') {
$errors[] = "{$line} 行 : すでにこの日時のチェックインデータが存在します。";
continue;
}
throw $e;
} catch (Throwable $e) {
DB::rollBack();
throw $e;
}
} }
if (!empty($errors)) { if (!empty($errors)) {

View File

@ -265,4 +265,19 @@ class CheckinCsvImporterTest extends TestCase
$this->assertSame(1, $user->ejaculations()->count()); $this->assertSame(1, $user->ejaculations()->count());
$this->assertEquals(Ejaculation::SOURCE_CSV, $ejaculation->source); $this->assertEquals(Ejaculation::SOURCE_CSV, $ejaculation->source);
} }
public function testDontThrowUniqueKeyViolation()
{
$user = factory(User::class)->create();
factory(Ejaculation::class)->create([
'user_id' => $user->id,
'ejaculated_date' => Carbon::create(2020, 1, 23, 6, 1, 0, 'Asia/Tokyo')
]);
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('2 行 : すでにこの日時のチェックインデータが存在します。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/date.utf8.csv');
$importer->execute();
}
} }