<?php
namespace JinDouYun\Cache;

use Mall\Framework\Factory;

class AllTableNameCache
{
    /**
     * 所有表名缓存
     *
     * @var
     */
    static $allTableName = 'all_tablename';

    /**
     * 判断所有表名缓存是否存在
     *
     * @param string $databaseName 库名
     *
     * @return bool
     */
    static function allTableNameCacheIsExists($databaseName){
        $result = Factory::cache('default')->has(self::$allTableName.'::'.$databaseName);
        return $result;
    }

    /**
     * 缓存制定库下的所有表名
     *
     * @param string $dataBaseName      当前数据库库名
     * @param array  $allTableNameData  当前库中所有表名数据
     *
     * @return null
     */
    static function allTableNameCache($databaseName, $allTableNameData)
    {
        if(empty($allTableNameData)){
            return false;
        }

        $pipe =  Factory::cache('default')->multi();
        foreach ($allTableNameData as $key => $value){
            $writeCache = Factory::cache('default')->sadd(self::$allTableName.'::'.$databaseName, $value['TABLE_NAME']);
        }
        $pipe->exec();
    }

    /**
     * 判断是否存在这张表
     *
     * @param string $dataBaseName    当前数据库库名
     * @param string $tableName       表名
     *
     * @return bool
     */
    static function TableIsExists($databaseName, $tableName)
    {
        $result =  Factory::cache('default')->sismember(self::$allTableName.'::'.$databaseName, $tableName);
        return $result;
    }

    /**
     * 添加新表到表名缓存中
     * @param string $dataBaseName    当前数据库库名
     * @param string $tableName       表名
     *
     * @return bool
     */
    static function addNewTableName($databaseName, $tableName){
        $writeCache = Factory::cache('default')->sadd(self::$allTableName.'::'.$databaseName, $tableName);
        return $writeCache;
    }

    /**
     * 获取指定库下所有表
     */
    static function getAllTableNameByDatabaseName($databaseName)
    {
        return Factory::cache('default')->smembers(self::$allTableName.'::'.$databaseName);
    }
}