Skip to content

Instantly share code, notes, and snippets.

@nicklasos
Last active August 29, 2015 14:02
Show Gist options
  • Save nicklasos/937213fa5c2f9ae33f71 to your computer and use it in GitHub Desktop.
Save nicklasos/937213fa5c2f9ae33f71 to your computer and use it in GitHub Desktop.
Insert random data to mongo
<?php
include __DIR__ . '/vendor/autoload.php';
$faker = Faker\Factory::create();
$randData = [
'gmt_diff' => 'randomDigitNotNull',
'ios_id' => 'uuid',
'email' => 'email',
'string' => 'word',
'integ' => 'randomDigitNotNull',
'version' => 'randomFloat',
];
function wtf($what)
{
echo '<pre>';
print_r($what);
echo '</pre>';
}
function users()
{
static $users = null;
if ($users === null) {
$users = (new Mongo())->selectCollection('mongoload', 'users');
}
return $users;
}
function get_random_data()
{
global $faker, $randData;
uksort($randData, function() { return rand() > rand(); });
$rand = rand(2, 5);
$data = [];
for ($i = 0; $i <= $rand; $i++) {
list($field, $method) = each($randData);
$data[$field] = $faker->$method;
}
return $data;
}
for ($i = 0; $i < 1000; $i++) {
$data = [];
for ($j = 0; $j < 1000; $j++) {
$data[] = get_random_data();
}
users()->batchInsert($data);
}
<?php
set_time_limit(600);
include __DIR__ . '/vendor/autoload.php';
$faker = Faker\Factory::create();
$randData = [
'gmt_diff' => 'randomDigitNotNull',
'ios_id' => 'uuid',
'email' => 'email',
'string' => 'word',
'integ' => 'randomDigitNotNull',
'version' => 'randomFloat',
];
function wtf($what)
{
echo '<pre>';
print_r($what);
echo '</pre>';
}
function db()
{
static $db = null;
if ($db === null) {
$db = new PDO('mysql:host=127.0.0.1;dbname=mongoload', 'root', '', [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "UTF8"']);
}
return $db;
}
function get_random_data()
{
global $faker, $randData;
uksort($randData, function() { return rand() > rand(); });
$rand = rand(2, 5);
$data = [];
for ($i = 0; $i <= $rand; $i++) {
list($field, $method) = each($randData);
$data[$field] = $faker->$method;
}
return $data;
}
function insert($data)
{
global $randData;
$fields = array_keys($randData);
$sql = "INSERT INTO users (" . implode(', ', $fields) . ") VALUES";
foreach ($data as $value) {
$sql .= " (";
foreach ($fields as $f) {
if (array_key_exists($f, $value)) {
$sql .= "'{$value[$f]}',";
} else {
$sql .= 'null,';
}
}
// remove last comma
$sql = substr($sql, 0, -1);
$sql .= "),";
}
$sql = substr($sql, 0, -1);
$stmt = db()->prepare($sql);
$stmt->execute();
}
for ($i = 0; $i < 10000; $i++) {
$data = [];
for ($j = 0; $j < 50; $j++) {
$data[] = get_random_data();
}
insert($data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment