11<?php
22
33use Illuminate \Database \Schema \Blueprint ;
4+ use Illuminate \Support \Facades \DB ;
45use Illuminate \Support \Facades \Schema ;
56use Studio \Totem \Database \TotemMigration ;
67
@@ -13,10 +14,7 @@ class UpdateTaskResultsDurationType extends TotemMigration
1314 */
1415 public function up ()
1516 {
16- Schema::connection (TOTEM_DATABASE_CONNECTION )
17- ->table (TOTEM_TABLE_PREFIX .'task_results ' , function (Blueprint $ table ) {
18- $ table ->decimal ('duration ' , 24 , 14 )->charset ('' )->collation ('' )->change ();
19- });
17+ $ this ->migrateDurationValues ();
2018 }
2119
2220 /**
@@ -26,9 +24,49 @@ public function up()
2624 */
2725 public function down ()
2826 {
27+ $ this ->migrateDurationValues (false );
28+ }
29+
30+ /**
31+ * @param bool $toFloat
32+ */
33+ private function migrateDurationValues (bool $ toFloat = true )
34+ {
35+ Schema::connection (TOTEM_DATABASE_CONNECTION )
36+ ->table (TOTEM_TABLE_PREFIX .'task_results ' , function (Blueprint $ table ) {
37+ // Move string duration column temporarily
38+ $ table ->renameColumn ('duration ' , 'duration_old ' );
39+ });
40+
41+ Schema::connection (TOTEM_DATABASE_CONNECTION )
42+ ->table (TOTEM_TABLE_PREFIX .'task_results ' , function (Blueprint $ table ) use ($ toFloat ) {
43+ // Create new decimal column
44+ if ($ toFloat ) {
45+ $ table ->decimal ('duration ' , 24 , 14 )->default (0.0 )->charset ('' )->collation ('' );
46+ } else {
47+ $ table ->string ('duration ' )->default ('' );
48+ }
49+ });
50+
51+ // Copy old duration data into new column
52+ DB ::connection (TOTEM_DATABASE_CONNECTION )
53+ ->table (TOTEM_TABLE_PREFIX .'task_results ' )
54+ ->select (['id ' , 'duration_old ' ])
55+ ->chunkById (100 , function ($ rows ) use ($ toFloat ) {
56+ foreach ($ rows as $ row ) {
57+ DB ::connection (TOTEM_DATABASE_CONNECTION )
58+ ->table (TOTEM_TABLE_PREFIX )
59+ ->where ('id ' , $ row ->id )
60+ ->update ([
61+ 'duration ' => $ toFloat ? floatval ($ row ->duration_old ) : (string ) $ row ->duration_old ,
62+ ]);
63+ }
64+ });
65+
2966 Schema::connection (TOTEM_DATABASE_CONNECTION )
3067 ->table (TOTEM_TABLE_PREFIX .'task_results ' , function (Blueprint $ table ) {
31- $ table ->string ('duration ' , 255 )->change ();
68+ // Remove temp column
69+ $ table ->dropColumn ('duration_old ' );
3270 });
3371 }
3472}
0 commit comments