gpt4 book ai didi

PHP 内存不足

转载 作者:可可西里 更新时间:2023-11-01 06:30:02 24 4
gpt4 key购买 nike

我正在尝试将 postgres 数据库中的数据插入到 mysql 数据库中。我需要导入大约 100000 条记录。但是我总是遇到内存不足的问题。

Out of memory (allocated 1705508864) (试图分配 222764 字节)

我正在使用 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 内存 (Windows 8) 的本地开发机器上执行此操作。 PHP版本:5.6.16

最佳答案

是的,您可以更改“内存限制”。但这只适用于今天,而不是明天,届时您将需要更多内存。

计划A:

相反,多写一点代码……将数据分 block ,比如说,一次分 block 1000 行。构建一个包含所有行的 INSERT 语句。自己在一个事务中执行。

B 计划:

构建一个包含所有行的 CSV 文件,然后使用 LOAD DATA INFILE 进行批量插入。

在任一计划中,避免一次将所有行加载到 RAM 中。 PHP 中的标量和数组有很多开销。

关于PHP 内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com