Skip to content

Instantly share code, notes, and snippets.

@AndrewRose
Last active August 29, 2015 13:56
Show Gist options
  • Save AndrewRose/8805629 to your computer and use it in GitHub Desktop.
Save AndrewRose/8805629 to your computer and use it in GitHub Desktop.
quickstore
<?php
/*
create table store(
id int primary key,
value blob -- 65535 bytes
);
*/
class quickStore
{
private $db;
private $zerofill;
public function __construct($dbname='tmp', $user='root', $pass='')
{
$this->db = new PDO('mysql:host=localhost;dbname='.$dbname, $user, $pass);
$this->zerofill = str_repeat("\0", 65535);
}
// initialise new key
public function initKey($key, $list=false)
{
$stmt = $this->db->prepare('insert into store(id, value) values(:k, :v)');
$stmt->execute([':k' => $key, ':v' => $list?$list:$this->zerofill]);
}
public function insert($key, $idx, $value)
{
$idx = ($idx*4);
echo "Inserting key: $key at idx: $idx\n";
$value = pack('L', (int)$value);
$stmt = $this->db->prepare('update store set value = concat(substring(value, 1, '.$idx.'), :v, substring(value, '.$idx.'+5, length(value))) where id = :k');
$stmt->bindParam(':k', $key);
$stmt->bindParam(':v', $value, PDO::PARAM_LOB);
$stmt->execute();
}
public function select($key, $idx, $range=1)
{
$idx = ($idx*4);
$range = ($range*4);
echo "Fetching key: $key at idx: $idx with range: $range\n";
$stmt = $this->db->prepare('select substring(value, '.$idx.'+1, '.$range.') as value from store where id = :k');
$stmt->execute([':k' => $key]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return unpack('L*', $row['value']);
}
}
$qs = new quickStore();
$qs->initKey(1);
$qs->initKey(2);
$qs->initKey(3);
$qs->insert(1, 1, 42);
$qs->insert(2, 2, 43);
$qs->insert(2, 3, 44);
$qs->insert(3, 3, 45);
print_r($qs->select(1, 1));
print_r($qs->select(2, 2, 2));
print_r($qs->select(3, 3));
@sangupta
Copy link

sangupta commented Feb 4, 2014

Hi Andrew - thanks for the code.

Thanks for the code and explanation. Some questions though:

  1. If we use BLOBs we need to load the entire list data in memory for reading paginated sets of lists
  2. Similarly, updates will get expensive

I was able to offset the read cost with a caching layer including minor updates.

The load expected is around 10-thousand line updates, with around 5-10 ids being added to the list at the end.

@AndrewRose
Copy link
Author

Hi Sandeep

MySQL will manage the caching of the BLOB as and when needed. Updates will also be managed in MySQL effectively so you shouldn't need to worry about your application using large amounts of memory.

I've added the ability to read ranges to the example code. When you say 10k updates .. how quickly do they need to be processed?

regards
Andrew

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment