I'm trying to do the following process in a Laravel migration:
Create a new table called client_log_partitions
. (DONE)
$table->create();
$table->bigIncrements('id')->unique();
$table->bigInteger('client_log_id');
$table->mediumText('partition_data');
$table->timestamps();
- I already have a table called
client_logs
with data stored in abigText()
column calledlog_data
. - Each row that already exists in the
client_logs
table needs to be split every 250 KB (or 250,000 characters since it should be single byte encoded) and then inserted into the newclient_log_partitions
table as partitions, with a reference to theclient_logs
entry it belongs to.
I know I may be able to achieve this using $table->postExecute()
, I just don't know what I might use to do so.
Once the data is moved to the new table, I then need to drop the log_data
column from client_logs
.
Normally, I would do this with a PHP script or something similar. But unfortunately I'm operating under circumstances where I'm unable to.
My question is, Is this doable using Laravel Migrations, and if so, how?
EDIT:
Although I'm unsure since i only whipped this up on the fly and haven't tested it, this is what I imagine the SQL for achieving this would look something like:
DROP PROCEDURE IF EXISTS PROCESS_LOG_DATA;
DROP PROCEDURE IF EXISTS PROCESS_LOG_ENTRIES;
DELIMITER ;;
## Procedure for processing a specific log entry
## and moving its data to the new table.
CREATE PROCEDURE PROCESS_LOG_DATA(log_id bigint, partition_size int)
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT LENGTH(log_data)/partition_size FROM client_logs where id=log_id INTO n;
SET i=0;
WHILE i<n DO
# Move the characters to the new table.
INSERT INTO client_log_partitions
(client_log_id, partition_data)
SELECT (id, LEFT(log_data, partition_size))
FROM client_logs
WHERE id=log_id
# Shift the characters off of the log_data
UPDATE client_logs
SET log_data = SUBSTR(
log_data,
partition_size,
LENGTH(log_data) - partition_size
) where id=log_id;
# Update the number of data partitions we've processed for this log entry
SET i = i + 1;
END WHILE;
End;
;;
## Procedure for processing all log entries
## and passing each one to the PROCESS_LOG_DATA procedure.
CREATE PROCEDURE PROCESS_LOG_ENTRIES(partition_size int)
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM client_logs INTO n;
SET i=0;
WHILE i<n DO
PROCESS_LOG_DATA(i, partition_size)
END WHILE;
End;
;;
DELIMIETER ;
## Process the log entries.
CALL PROCESS_LOG_ENTRIES(250000);