Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- const DBHOST = 'localhost';
- CONST DBPORT = '3306';
- const DBNAME = 'test';
- const DBUSER = 'root';
- const DBPASS = '';
- withDb(function($db) {
- $total = 0;
- foreach (uidGenerator(1000) as $uid) {
- migrateUser($uid);
- $total++;
- }
- echo "Total users migrated:$total\n";
- });
- function uidGenerator($limit) {
- $uids = [];
- $lastId = 0;
- while (true) {
- $uids = [];
- withDb(function($db) use (&$uids, $lastId, $limit) {
- $selectUsers = $db->prepare('SELECT uid from tbl_member WHERE uid > :lastId AND col1 > 0 ORDER BY uid ASC LIMIT :limit');
- $selectUsers->bindParam(':lastId', $lastId, PDO::PARAM_INT);
- $selectUsers->bindParam(':limit', $limit, PDO::PARAM_INT);
- $selectUsers->execute();
- foreach($selectUsers->fetchAll() as $user) {
- $uids []= $user['uid'];
- }
- $selectUsers->closeCursor();
- });
- if (! $uids) {
- break;
- }
- foreach ($uids as $uid) {
- yield $uid;
- }
- $lastId = end($uids);
- }
- }
- function migrateUser($uid) {
- echo "Migrating user: $uid \n";
- withTransaction(function(PDO $db) use ($uid) {
- $selectMember = $db->prepare('SELECT col1 FROM tbl_member WHERE uid = :uid FOR UPDATE');
- $updateMember = $db->prepare('UPDATE tbl_member SET col1 = :col1 WHERE uid = :uid');
- $insertLog = $db->prepare('INSERT INTO tbl_member_log (uid, oldCol1, newCol1) VALUES (:uid, :oldCol1, newCol1)');
- $selectMember->execute([':uid' => $uid]);
- $member = $selectMember->fetch();
- $newCol1 = bcadd($member['col1'], 100, 2);
- $updateMember->execute([
- ':uid' => $uid,
- ':col1' => $newCol1,
- ]);
- $insertLog->execute([
- ':uid' => $uid,
- ':oldCol1' => $member['col1'],
- ':newCol1' => $newCol1,
- ]);
- $selectMember->closeCursor();
- $updateMember->closeCursor();
- $insertLog->closeCursor();
- });
- }
- function withTransaction($func) {
- withDb(function(PDO $db) use ($func) {
- try {
- $db->beginTransaction();
- $func($db);
- $db->commit();
- } catch (Exception $e) {
- $db->rollBack();
- throw $e;
- }
- });
- }
- function withDb($func) {
- static $dbh = null;
- try {
- if ($dbh === null) {
- $dbh = new PDO(sprintf('mysql:host=%s;dbname=%s;charset=UTF8;port=%s', DBHOST, DBNAME, DBPORT), DBUSER, DBPASS);
- if (! $dbh) {
- throw new \Exception('Can not connect to database!');
- }
- }
- $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $func($dbh);
- } catch (PDOException $e) {
- print "Error!: " . $e->getMessage() . PHP_EOL;
- die();
- }
- }
Add Comment
Please, Sign In to add comment