Horisontal sharding

Hello!

Another question about splitting data over multiple databases. Now about "Horisontal Sharding" http://docs.phalconphp.com/en/latest/reference/models.html#setting-multiple-databases

I know that using function selectReadConnection I can choose right connection according to the current query conditions when I want retrieve data from the database.

But, how to choose right connection when I want put (INSERT, UPDATE) data in the database?



85.4k

The idea of 'selectReadConnection' is reduce the read load by splitting queries over several databases servers, write operations are performed in a single master database server which replicates the data to the slaves in async mode.



26.9k

Thank you for the reply! I thought that it works exactly how you explained... Do you plan to add feature such as "selectWriteConnection"?



85.4k

By simply override the getWriteConnection in a model you can dynamically change the connection used to write data:

<?php

class Robots extends Phalcon\Mvc\Model
{
    public static function getWriteConnection()
    {
        if ($this->shardKey == 'abcd') {
            return $this->getDI()->get('dbMysql1');
        }
        if ($this->shardKey == 'efgh') {
            return $this->getDI()->get('dbMysql2');
        }
        return $this->getDI()->get('dbMysql3');
    }
}


26.9k

Thank you! So, when I save object I just need check its properties and choose the right connection in the overrided function getWriteConnection. Sure there is still present problem with the null ID (INSERT case), but it's looks okay!