package ru.yandex.webmaster3.storage.clickhouse.system.dao;

import ru.yandex.webmaster3.storage.clickhouse.system.data.ClickhouseSystemColumnInfo;
import ru.yandex.webmaster3.storage.util.clickhouse2.AbstractClickhouseDao;
import ru.yandex.webmaster3.storage.util.clickhouse2.ClickhouseException;
import ru.yandex.webmaster3.storage.util.clickhouse2.ClickhouseHost;
import ru.yandex.webmaster3.storage.util.clickhouse2.query.QueryBuilder;

import java.util.List;

/**
 * @author avhaliullin
 */
public class ClickhouseSystemColumnsCHDao extends AbstractClickhouseDao {
    private static final String TABLE_NAME = "system.columns";

    public List<ClickhouseSystemColumnInfo> getColumnsForTable(ClickhouseHost clickhouseHost, String databaseName, String tableName) throws ClickhouseException {
        return getClickhouseServer().executeWithFixedHost(clickhouseHost, () -> queryAll(
                QueryBuilder.select(F.NAME, F.TYPE)
                        .from(TABLE_NAME)
                        .where(QueryBuilder.eq(F.DATABASE, databaseName))
                        .and(QueryBuilder.eq(F.TABLE, tableName)),
                row -> new ClickhouseSystemColumnInfo(databaseName, tableName, row.getString(F.NAME), row.getString(F.TYPE))
        ));
    }

    private static class F {
        static final String DATABASE = "database";
        static final String TABLE = "table";
        static final String NAME = "name";
        static final String TYPE = "type";
    }
}
