我正在尝试将Postgres数据库中的数据插入到MySQL数据库中。 我需要导入约100000
条记录。 但是,我总是遇到内存不足的问题。
Out of memory (allocated 1705508864) (tried to allocate 222764 bytes)
我在使用Laravel 5进行操作,以下是代码:
// to avoid memory limit or time out issue
ini_set('memory_limit', '-1');
ini_set('max_input_time', '-1');
ini_set('max_execution_time', '0');
set_time_limit(0);
// this speeds up things a bit
DB::disableQueryLog();
$importableModels = [
// array of table names
];
$failedChunks = 0;
foreach ($importableModels as $postGresModel => $mysqlModel) {
$total = $postGresModel::count();
$chunkSize = getChunkSize($total);
// customize chunk size in case of certain tables to avoid too many place holders error
if ($postGresModel === 'ApplicationFormsPostgres') {
$chunkSize = 300;
}
$class = 'App\\Models\\' . $mysqlModel;
$object = new $class;
// trucate prev data //
Eloquent::unguard();
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$object->truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Eloquent::reguard();
$postGresModel::chunk($chunkSize, function ($chunk) use ($postGresModel, $mysqlModel, $failedChunks, $object) {
// make any adjustments
$fixedChunk = $chunk->map(function ($item, $key) use ($postGresModel) {
$appendableAttributes = $postGresModel::APPEND_FIELDS;
$attributes = $item->getAttributes();
// replace null/no values with empty string
foreach ($attributes as $key => $attribute) {
if ($attribute === null) {
$attributes[$key] = '';
}
}
// add customized attributes and values
foreach ($appendableAttributes as $appendField) {
if ($appendField === 'ssn') {
$value = $attributes['number'];
$attributes[$appendField] = substr($value, 0, 4);
} else {
$attributes[$appendField] = '';
}
}
return $attributes;
});
// insert chunk of data in db now
if (!$object->insert($fixedChunk->toArray())) {
$failedChunks++;
}
});
}
当插入大约80000
行后,内存问题会出现。
我怀疑是集合map
函数或map函数内部的循环有问题。我甚至尝试将内存设置和时间限制设置为无限制,但都没有用。也许需要使用引用变量之类的东西,但我不确定如何操作。
上述代码是否可以进行任何优化以减少内存使用?
或者如何通过代码高效地从大型PostgreSQL数据库导入大量数据到MySQL?
有人能告诉我在这里做错了什么或为什么整个内存被消耗掉了吗?
PS:我正在使用具有4GB RAM(Windows 8)的本地开发机。PHP版本:5.6.16
1705508864
字节,相当于1705MB/1.7GB
。也许代码有问题,但我在代码中找不到优化点:( - dev02