public function add($item_id, $quantity) { $batches = array(); $local_txn = $this->claimStart(); $table = $this->table(); $sql_add = "INSERT OR IGNORE INTO `{$table}` " . "(`user_id`, `item_id`, `serial`, `properties`, `soft_delete`) " . "VALUES (%i, %i, %i, %s, 0)"; $sql_update = "UPDATE `{$table}` SET `properties` = %s, `soft_delete` = 0 " . "WHERE `user_id` = %i AND `item_id` = %i AND `serial` = %i"; foreach ($quantity->all() as $serial => $properties) { $properties = json_encode($properties); $rs = $this->execute($sql_add, $this->user_id, $item_id, $serial, $properties); if ($rs->affected() < 1) { $rs = $this->execute($sql_update, $properties, $this->user_id, $item_id, $serial); if ($rs->affected() < 1) { if ($local_txn) { Transaction::rollback(); } throw new Exception('database error', $this->dbInfo()); } } } if ($local_txn) { if (!Transaction::commit()) { throw new Exception('database error', $this->dbInfo()); } } return TRUE; }
public function subtract($item_id, $quantity) { $local_txn = $this->claimStart(); $table = $this->table(); $sql = "UPDATE `{$table}` SET `quantity` = `quantity` - %i " . "WHERE user_id = %i AND `item_id` = %i AND `quantity` >= %i"; $rs = $this->execute($sql, $quantity, $this->user_id, $item_id, $quantity); if ($rs->affected() < 1) { if ($local_txn) { Transaction::rollback(); } throw new Exception('not enough', $this->dbInfo()); } $sql = "SELECT `quantity` FROM `{$table}` WHERE `user_id` = %i AND `item_id` = %i"; $rs = $this->execute($sql, $this->user_id, $item_id); $row = $rs->fetch(); $rs->free(); if (!$row) { if ($local_txn) { Transaction::rollback(); } throw new Exception('database error', $this->dbInfo()); } if ($local_txn) { if (!Transaction::commit()) { throw new Exception('database error', $this->dbInfo()); } } return $row['quantity']; }
public function rollback($auth = NULL) { if ($auth != Transaction::SIGNATURE) { return Transaction::rollback(); } if (!$this->txn) { return parent::rollback(); } if ($this->lock) { return TRUE; } Connection::remove($this); $rs = parent::rollback(); $this->lock = TRUE; return $rs; }
//var_dump( $conn1 ); Transaction::reset(); Tap::ok(Transaction::start(), 'started a transaction at the global level'); $conn1 = $newconn(); $conn2 = $newconn(); Tap::ok($conn1->start(), 'started a transaction on conn1'); Tap::ok($conn2->start(), 'started a transaction on conn2'); $rs = $conn1->execute("insert into {$table} values (3)"); Tap::ok($rs, 'inserted a row into test table from conn1'); //if( ! $rs ) Tap::debug( $conn1 ); $rs = $conn2->execute("insert into {$table} values(4)"); Tap::ok($rs, 'inserted a row into test table from conn2'); //if( ! $rs ) Tap::debug( $conn2 ); Tap::ok($conn1->commit(), 'committed inserted row on conn1'); Tap::ok($conn2->commit(), 'committed inserted row on conn2'); Tap::ok(Transaction::rollback(), 'rolled back the transaction at the global level'); Tap::ok($rs = $dbmain->execute("select id from {$table}"), 'selected all rows from the table'); $ct = $rs->affected(); Tap::is($ct, 2, '2 rows in the table, new rows rolled back'); $rs = $conn1->execute("select id from {$table}"); Tap::is($rs, FALSE, 'after rolling back, new queries fail on rolled back db object'); $dbmain->execute("drop table {$table}"); $db = $newconn(); $raw = file_get_contents(__DIR__ . '/../sample/i_can_eat_glass.txt'); $lines = explode("\n", $raw); $lines = array_slice($lines, 0, 10) + array_slice($lines, 100, 10) + array_slice($lines, 200, 10) + array_slice($lines, 200, 10); $raw = implode("\n", $lines); $sql = "CREATE TEMPORARY TABLE t1utf8 (`i` INT UNSIGNED NOT NULL PRIMARY KEY, `line` VARCHAR(5000) ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8"; $db->execute($sql); foreach ($lines as $i => $line) { //$lines[ $i ] = $line = mb_convert_encoding($line, 'UTF-8', 'auto');
<?php namespace Gaia\Stockpile; use Gaia\DB\Transaction; use Gaia\Test\Tap; $user_id = uniqueUserID(); $item_id = uniqueNumber(1, 1000000); // test transaction support. Transaction::claimStart(); $total = stockpile($app, $user_id)->add($item_id); Tap::is(quantify($total), 4, 'add inside a transaction'); // revert the transaction Transaction::rollback(); $total = stockpile($app, $user_id)->get($item_id); Tap::is(quantify($total), 3, 'after txn rollback, the value we added isnt there'); // add inside a transaction and commit it. Transaction::claimStart(); $total = stockpile($app, $user_id)->add($item_id); Tranaction::commit(); $total = stockpile($app, $user_id)->get($item_id); Tap::is(quantify($total), 4, 'add inside of a transaction and commit it. now we can see it!');
public function handle(\Exception $e) { if (Transaction::inProgress()) { Transaction::rollback(); } return $e; }
/** * rollback a transaction. * connected to the Transaction singleton to support multi-database transactions. */ public function rollback() { $args = func_get_args(); $auth = isset($args[0]) ? $args[0] : NULL; if ($this->core instanceof Iface) { return $this->core->rollback($auth); } if ($auth != Transaction::SIGNATURE) { return Transaction::rollback(); } if (!$this->txn) { return FALSE; } if ($this->lock) { return TRUE; } $f = $this->_[__FUNCTION__]; $res = (bool) $f($auth); $this->lock = TRUE; return $res; }
/** * bid on an item * only works with those listings that set an opening bid (even if that amount is zero). * We use the proxy-bid system here, as used by ebay: * @see http://en.wikipedia.org/wiki/Proxy_bid * the winning bidder pays the price of the second-highest bid plus the step */ public function bid($id, $bid, array $data = NULL) { // normalize the data. $data = new Store\KVP($data); // create an internal transaction if no transaction has been passed in. Transaction::start(); try { // we assume the current user is always the bidder $bidder = $this->user(); // if no bidder was passed into the constructor, blow up. if (!Souk\Util::validatePositiveInteger($bidder)) { throw new Exception('invalid bidder', $bidder); } // get a row lock on the listing. $listing = $this->get($id, TRUE); if (!$listing || !$listing->id) { throw new Exception('not found', $id); } // need the current time to do some comparisons. $ts = Souk\util::now(); // don't go anywhere if the bidding is already closed. if ($listing->closed) { throw new Exception('closed', $listing); } // can't let the seller bid on the listing. if ($listing->seller == $bidder) { throw new Exception('invalid bidder', $listing); } // step is set when it is a biddable item. if it isn't there, don't allow bidding. if ($listing->step < 1) { throw new Exception('buy only', $listing); } // has time expired on this listing? if ($listing->expires <= $ts) { throw new Exception('expired', $listing); } // make sure we bid enough to challenge the current bid level. // if proxy bidding is enabled we still might not win the bid, // but at least we pushed it up a bit. if ($listing->bid + $listing->step > $bid) { throw new Exception('too low', $listing); } // keep a pristine copy of the listing internally so other wrapper classes can compare // afterward and see what changes were made. // The Souk\stockpile adapter especially needs this so it can return escrowed bids // to the previous bidder. $listing->setPriorState($listing); // if proxy bidding is enabled, this gets a little more complicated. // proxy bidding is where you bid the max you are willing to pay, but only pay // one step above the previous bidder's level. // This is how ebay runs its auction site. // this means when you bid, we track your max amount you are willing to spend, but only // bid the minimum. When the next bid comes in, we automatically up your bid for you // until you go over your max amount and someone else takes the lead. // this approach makes the escrow system more efficient as well since it can excrow your // maximum amount all at once, and then refund when you get outbid or refund the difference // if you get it for a lower bid. if ($data->enable_proxy) { // looks like the previous bidder got outbid. // track their maximum amount, and set the bid based on one step above the previous bid. if ($bid >= $listing->proxybid + $listing->step) { $listing->bid = $listing->proxybid + $listing->step; $listing->proxybid = $bid; $listing->bidder = $bidder; $listing->bidcount = $listing->bidcount + 1; // the other bidder is still the winner of the bid. our bid didn't go over their // max bid amount. Bump up their bid amount to what we bid, and increment the // bid count by 2, since we bid on it, and they bid back. } else { $listing->bid = $bid; $listing->bidcount = $listing->bidcount + 2; } // in this case, not a proxy bid system, just a straight up english auction. // don't worry about previous bidder. we know we bid more than the previous bidder, // so pump up the bid to whatever we passed in. } else { $listing->bid = $bid; $listing->bidder = $bidder; $listing->bidcount = $listing->bidcount + 1; } $listing->touch = $ts; $this->storage()->bid($listing); Transaction::commit(); // done. return $listing; // something went wrong ... } catch (Exception $e) { // revert the transaction ... // if it was created internally, remove it. Transaction::rollback(); // toss the exception again. throw $e; } }
/** * @see Souk::close() * close the bid and transfer currency from escrow into seller, and items to buyer. */ function close($id, array $data = NULL) { // wrap in try catch so we can manage transactions. try { // kick off a transaction if not attached already. Transaction::start(); // do the core logic of closing the listing. $listing = $this->prepListing($this->core->close($id)); // did someone successfully buy this listing? if ($listing->buyer) { // settle up! // start by transferring funds from the buyer's escrow to the seller's currency account. $buyer = $this->transfer($this->currencyEscrow($listing->buyer), $this->currencyAccount($listing->seller)); // subtract moves money from escrow into seller's currency. $buyer->subtract($this->currencyId(), $listing->bid, $this->prepData($data, $listing, 'pay_seller')); // set up a transfer between the buyer's item account and the seller's escrow $buyer = $this->transfer($this->itemAccount($listing->buyer), $this->itemEscrow($listing->seller)); // now, move the item from escrow into the buyer's item account. $buyer->add($listing->item_id, $listing->quantity, $this->prepData($data, $listing, 'winbid')); // the buyer only pays the bid amount, not the max they were willing to pay, // since this is a proxy bid system. // that means if we escrowed extra money, we return it now. if ($listing->proxybid > $listing->bid) { // figure out how much extra was escrowed. $diff = $listing->proxybid - $listing->bid; // set up a transfer between currency escrow and the buyer's currency account. $buyer = $this->transfer($this->currencyAccount($listing->buyer), $this->currencyEscrow($listing->buyer)); // return the funds. $buyer->add($this->currencyId(), $diff); } // no one won the bid? WTF? Return the item to the owner. } else { // set up a transfer between the seller and their escrow account. $seller = $this->transfer($this->itemAccount($listing->seller), $this->itemEscrow($listing->seller)); // return the item from the listing. $seller->add($listing->item_id, $listing->quantity, $this->prepData($data, $listing, 'no_sale')); // if anyone bid on the listing, return their escrowed bid ... this happens if the reserve isn't met. $this->cancelBid($listing, $data); } // commit the transaction if we started one internally. Transaction::commit(); // all done. return $listing; } catch (Exception $e) { // what happened? roll back the transaction Transaction::rollback(); // exception, get your freak on! Fly! be free! throw $e; } }
/** * @see Stockpile_Interface::subtract(); */ public function subtract($item_id, $quantity = 1, array $data = NULL) { Transaction::start(); try { if (!$quantity instanceof Stockpile_HybridQuantity) { $quantity = $this->get($item_id)->grab($quantity); } if ($quantity->value() < 1) { throw $this->handle(new Stockpile_Exception('cannot subtract: invalid quantity', $quantity)); } if ($quantity->tally() > 0) { $tally = $this->core->subtract($item_id, $quantity->tally(), $data); } else { $tally = $this->core->get($item_id, $with_lock = TRUE); } if (count($quantity->all()) > 0) { $serial = $this->serial->subtract($item_id, $quantity->all(), $data); } else { $serial = $this->serial->get($item_id); } if (!Transaction::commit()) { throw new Exception('database error'); } return $this->quantity(array('tally' => $tally, 'serial' => $serial)); } catch (\Exception $e) { if (Transaction::inProgress()) { Transaction::rollback(); } $e = new Exception('cannot subtract: ' . $e->getMessage(), $e->__toString()); throw $e; } }
public function rollback($auth = NULL) { if ($auth != Transaction::SIGNATURE) { return Transaction::rollback(); } if (!$this->txn) { return parent::query('ROLLBACK'); } if ($this->lock) { return TRUE; } $rs = parent::query('ROLLBACK'); $this->lock = TRUE; return $rs; }
public function trans_rollback($auth = NULL) { if ($auth != Transaction::SIGNATURE) { return Transaction::rollback(); } if (!$this->txn) { return $this->core->trans_rollback(); } if ($this->lock) { return TRUE; } $rs = $this->core->trans_rollback(); $this->close(); $this->lock = TRUE; return $rs; }