Skip to content

Instantly share code, notes, and snippets.

@c9s
Last active February 4, 2017 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c9s/f9685939e0ec777a6f917655fb824c5b to your computer and use it in GitHub Desktop.
Save c9s/f9685939e0ec777a6f917655fb824c5b to your computer and use it in GitHub Desktop.

Defining shards

sharding:
  mappings:
    M_store_id:
      tables: ["orders"]
      key: "store_id"
      hash:
        target1: order_shard_1
        target2: order_shard_2
data_source:
  default: sqlite
  nodes:
    master:
      dsn: 'mysql:host=localhost;dbname=testing'
      user: root
    order_shard_1:
      dsn: 'mysql:host=order_shard_1;dbname=testing'
      user: root
    order_shard_2:
      dsn: 'mysql:host=order_shard_2;dbname=testing'
      user: root

Defining shard key

In your model schema file, simply define shardBy to define your shard key. The shard key must be unique:

class OrderSchema extends DeclareSchema {
  public function schema() {
    $this->shardBy("store_id");
  }
}

Defining global table

The global table spreads insert/update/delete statement of a record across different shards:

class StoreSchema extends DeclareSchema {
  public function schema() {
    $this->global();
  }
}

$store->update([ ...  ]); // This will update store record to all shards

Querying data from shards

$shards = Order::shards(); // returns ShardDispatcher of the model.

// Dispatch to one repository by $key and create the record in the repository.
Order::shards()->dispatch($key)->create($args);

// Automatically dispatch the repository by the "key" defined in $args.
Order::shards()->create($args);

$order = Order::shards()->find(77890);

$order = Order::shards()->find('569f21d7-fcad-49bf-99dd-795be631f984');

QueryDispatcher

$stms = Order::shards()->query($query);
foreach ($stms as $shardId => $stm) {
  $res = $stm->fetch();
  // ....
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment