<?php

require __DIR__ . '../vendor/autoload.php';

require_once( ABSPATH . 'wp-config.php' );

$wpdb->hash_map = new Flexihash(null, R2DB_FLEXIHASH_REPLICAS);

/* Hashing function to map blogs to databases.
 *
 * Implements a consistent hashing scheme using Flexihash.
 */
function noblogs_db_callback($query, $wpdb) {
  $wpdb_hash = $wpdb->hash_map;
  if (preg_match("/^{$wpdb->base_prefix}(\d+)_/", $wpdb->table, $matches)) {
    $blog_id = $matches[1];
    return $wpdb_hash->lookup($blog_id);
  }
}
$wpdb->add_callback('noblogs_db_callback');