SQLAzureShardManager.php 5.38 KB
Newer Older
1 2 3 4 5
<?php

namespace Doctrine\DBAL\Sharding\SQLAzure;

use Doctrine\DBAL\Connection;
6 7
use Doctrine\DBAL\Sharding\ShardingException;
use Doctrine\DBAL\Sharding\ShardManager;
8
use Doctrine\DBAL\Types\Type;
9
use RuntimeException;
10
use function sprintf;
11 12 13 14 15 16

/**
 * Sharding using the SQL Azure Federations support.
 */
class SQLAzureShardManager implements ShardManager
{
17
    /** @var string */
18 19
    private $federationName;

20
    /** @var bool */
21 22
    private $filteringEnabled;

23
    /** @var string */
24 25
    private $distributionKey;

26
    /** @var string */
27 28
    private $distributionType;

29
    /** @var Connection */
30 31
    private $conn;

32
    /** @var string|null */
33 34 35
    private $currentDistributionValue;

    /**
36
     * @throws ShardingException
37 38 39 40
     */
    public function __construct(Connection $conn)
    {
        $this->conn = $conn;
41
        $params     = $conn->getParams();
42

43
        if (! isset($params['sharding']['federationName'])) {
44 45 46
            throw ShardingException::missingDefaultFederationName();
        }

47
        if (! isset($params['sharding']['distributionKey'])) {
48 49 50
            throw ShardingException::missingDefaultDistributionKey();
        }

51
        if (! isset($params['sharding']['distributionType'])) {
52 53 54
            throw ShardingException::missingDistributionType();
        }

55 56
        $this->federationName   = $params['sharding']['federationName'];
        $this->distributionKey  = $params['sharding']['distributionKey'];
57
        $this->distributionType = $params['sharding']['distributionType'];
58
        $this->filteringEnabled = (bool) ($params['sharding']['filteringEnabled'] ?? false);
59 60 61
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
62
     * Gets the name of the federation.
63 64 65 66 67 68 69 70 71
     *
     * @return string
     */
    public function getFederationName()
    {
        return $this->federationName;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
72
     * Gets the distribution key.
73 74 75 76 77 78 79 80 81
     *
     * @return string
     */
    public function getDistributionKey()
    {
        return $this->distributionKey;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
82
     * Gets the Doctrine Type name used for the distribution.
83 84 85 86 87 88 89 90 91
     *
     * @return string
     */
    public function getDistributionType()
    {
        return $this->distributionType;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
92 93
     * Sets Enabled/Disable filtering on the fly.
     *
94
     * @param bool $flag
95 96 97 98 99
     *
     * @return void
     */
    public function setFilteringEnabled($flag)
    {
100
        $this->filteringEnabled = (bool) $flag;
101 102 103 104 105 106 107 108 109 110 111
    }

    /**
     * {@inheritDoc}
     */
    public function selectGlobal()
    {
        if ($this->conn->isTransactionActive()) {
            throw ShardingException::activeTransaction();
        }

112
        $sql = 'USE FEDERATION ROOT WITH RESET';
113 114 115 116 117 118 119 120 121 122 123 124 125 126
        $this->conn->exec($sql);
        $this->currentDistributionValue = null;
    }

    /**
     * {@inheritDoc}
     */
    public function selectShard($distributionValue)
    {
        if ($this->conn->isTransactionActive()) {
            throw ShardingException::activeTransaction();
        }

        $platform = $this->conn->getDatabasePlatform();
127 128
        $sql      = sprintf(
            'USE FEDERATION %s (%s = %s) WITH RESET, FILTERING = %s;',
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
            $platform->quoteIdentifier($this->federationName),
            $platform->quoteIdentifier($this->distributionKey),
            $this->conn->quote($distributionValue),
            ($this->filteringEnabled ? 'ON' : 'OFF')
        );

        $this->conn->exec($sql);
        $this->currentDistributionValue = $distributionValue;
    }

    /**
     * {@inheritDoc}
     */
    public function getCurrentDistributionValue()
    {
        return $this->currentDistributionValue;
    }

    /**
     * {@inheritDoc}
     */
    public function getShards()
    {
152
        $sql = 'SELECT member_id as id,
153 154 155 156 157
                      distribution_name as distribution_key,
                      CAST(range_low AS CHAR) AS rangeLow,
                      CAST(range_high AS CHAR) AS rangeHigh
                      FROM sys.federation_member_distributions d
                      INNER JOIN sys.federations f ON f.federation_id = d.federation_id
158
                      WHERE f.name = ' . $this->conn->quote($this->federationName);
159

160 161 162 163 164 165
        return $this->conn->fetchAll($sql);
    }

     /**
      * {@inheritDoc}
      */
166
    public function queryAll($sql, array $params = [], array $types = [])
167 168
    {
        $shards = $this->getShards();
169 170
        if (! $shards) {
            throw new RuntimeException('No shards found for ' . $this->federationName);
171 172
        }

173
        $result          = [];
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        $oldDistribution = $this->getCurrentDistributionValue();

        foreach ($shards as $shard) {
            $this->selectShard($shard['rangeLow']);
            foreach ($this->conn->fetchAll($sql, $params, $types) as $row) {
                $result[] = $row;
            }
        }

        if ($oldDistribution === null) {
            $this->selectGlobal();
        } else {
            $this->selectShard($oldDistribution);
        }

        return $result;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
193
     * Splits Federation at a given distribution value.
194 195
     *
     * @param mixed $splitDistributionValue
Benjamin Morel's avatar
Benjamin Morel committed
196 197
     *
     * @return void
198 199 200 201 202
     */
    public function splitFederation($splitDistributionValue)
    {
        $type = Type::getType($this->distributionType);

203 204 205
        $sql = 'ALTER FEDERATION ' . $this->getFederationName() . ' ' .
               'SPLIT AT (' . $this->getDistributionKey() . ' = ' .
               $this->conn->quote($splitDistributionValue, $type->getBindingType()) . ')';
206 207 208
        $this->conn->exec($sql);
    }
}