<?php
namespace nur\sery\db\mysql;

use nur\sery\db\CapacitorChannel;
use nur\sery\db\CapacitorStorage;

/**
 * Class MysqlStorage
 */
class MysqlStorage extends CapacitorStorage {
  function __construct($mysql) {
    $this->db = Mysql::with($mysql);
  }

  /** @var Mysql */
  protected $db;

  function db(): Mysql {
    return $this->db;
  }

  const PRIMARY_KEY_DEFINITION = [
    "id_" => "integer primary key auto_increment",
  ];

  function _getCreateSql(CapacitorChannel $channel): string {
    $query = new _query_base($this->_createSql($channel));
    return self::format_sql($channel, $query->getSql());
  }

  function _exists(CapacitorChannel $channel): bool {
    $db = $this->db;
    $tableName = $db->get([
      "select table_name from information_schema.tables",
      "where" => [
        "table_schema" => $db->getDbname(),
        "table_name" => $channel->getTableName(),
      ],
    ]);
    return $tableName !== null;
  }

  function close(): void {
    $this->db->close();
  }
}
