FrankChen021 commented on code in PR #13165:
URL: https://github.com/apache/druid/pull/13165#discussion_r1000596453


##########
extensions-core/druid-catalog/pom.xml:
##########
@@ -0,0 +1,328 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements.  See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership.  The ASF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License.  You may obtain a copy of the License at
+  ~
+  ~   http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied.  See the License for the
+  ~ specific language governing permissions and limitations
+  ~ under the License.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>org.apache.druid.extensions</groupId>
+    <artifactId>druid-catalog</artifactId>
+    <name>druid-catalog</name>
+    <description>Druid Catalog</description>
+
+    <parent>
+        <groupId>org.apache.druid</groupId>
+        <artifactId>druid</artifactId>
+        <version>25.0.0-SNAPSHOT</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-core</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-processing</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-server</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-indexing-service</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-sql</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-services</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.inject</groupId>
+            <artifactId>guice</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.inject.extensions</groupId>
+            <artifactId>guice-multibindings</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.opencsv</groupId>
+            <artifactId>opencsv</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-databind</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-annotations</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.validation</groupId>
+            <artifactId>validation-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.code.findbugs</groupId>
+            <artifactId>jsr305</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>jakarta.inject</groupId>
+            <artifactId>jakarta.inject-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>joda-time</groupId>
+            <artifactId>joda-time</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.netty</groupId>
+            <artifactId>netty</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.calcite</groupId>
+            <artifactId>calcite-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+               <dependency>

Review Comment:
   indent problem



##########
extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/storage/sql/SQLCatalogManager.java:
##########
@@ -0,0 +1,578 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.storage.sql;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.inject.Inject;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.TableMetadata;
+import org.apache.druid.catalog.model.TableSpec;
+import org.apache.druid.catalog.storage.MetastoreManager;
+import org.apache.druid.guice.ManageLifecycle;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
+import org.apache.druid.metadata.SQLMetadataConnector;
+import org.skife.jdbi.v2.Handle;
+import org.skife.jdbi.v2.IDBI;
+import org.skife.jdbi.v2.Query;
+import org.skife.jdbi.v2.ResultIterator;
+import org.skife.jdbi.v2.Update;
+import org.skife.jdbi.v2.exceptions.CallbackFailedException;
+import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;
+import org.skife.jdbi.v2.tweak.HandleCallback;
+
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.function.Function;
+
+@ManageLifecycle
+public class SQLCatalogManager implements CatalogManager
+{
+  public static final String TABLES_TABLE = "tableDefs";
+
+  private static final String INSERT_TABLE =
+      "INSERT INTO %s\n" +
+      "  (schemaName, name, creationTime, updateTime, state, payload)\n" +
+      "  VALUES(:schemaName, :name, :creationTime, :updateTime, :state, 
:payload)";
+
+  private static final String UPDATE_HEAD =
+      "UPDATE %s\n SET\n";
+
+  private static final String WHERE_TABLE_ID =
+      "WHERE schemaName = :schemaName\n" +
+      "  AND name = :name\n";
+
+  private static final String SAFETY_CHECK =
+      "  AND updateTime = :oldVersion";
+
+  private static final String UPDATE_DEFN_UNSAFE =
+      UPDATE_HEAD +
+      "  payload = :payload,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String UPDATE_DEFN_SAFE =
+      UPDATE_DEFN_UNSAFE +
+      SAFETY_CHECK;
+
+  private static final String UPDATE_STATE =
+      UPDATE_HEAD +
+      "  state = :state,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_TABLE =
+      "SELECT creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_PAYLOAD =
+      "SELECT state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_ALL_TABLES =
+      "SELECT schemaName, name\n" +
+      "FROM %s\n" +
+      "ORDER BY schemaName, name";
+
+  private static final String SELECT_TABLES_IN_SCHEMA =
+      "SELECT name\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String SELECT_TABLE_DETAILS_IN_SCHEMA =
+      "SELECT name, creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String DELETE_TABLE =
+      "DELETE FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private final MetastoreManager metastoreManager;
+  private final SQLMetadataConnector connector;
+  private final ObjectMapper jsonMapper;
+  private final IDBI dbi;
+  private final String tableName;
+  private final Deque<Listener> listeners = new ConcurrentLinkedDeque<>();
+
+  @Inject
+  public SQLCatalogManager(MetastoreManager metastoreManager)
+  {
+    if (!metastoreManager.isSql()) {
+      throw new ISE("SQLCatalogManager only works with SQL based metadata 
store at this time");
+    }
+    this.metastoreManager = metastoreManager;
+    this.connector = metastoreManager.sqlConnector();
+    this.dbi = connector.getDBI();
+    this.jsonMapper = metastoreManager.jsonMapper();
+    this.tableName = getTableDefnTable();
+  }
+
+  @Override
+  @LifecycleStart
+  public void start()
+  {
+    createTableDefnTable();
+  }
+
+  @Override
+  public void stop()
+  {
+  }
+
+  // Mimics what MetadataStorageTablesConfig should do.
+  public String getTableDefnTable()
+  {
+    final String base = metastoreManager.tablesConfig().getBase();
+    if (Strings.isNullOrEmpty(base)) {
+      return TABLES_TABLE;
+    } else {
+      return StringUtils.format("%s_%s", base, TABLES_TABLE);
+    }
+  }
+
+  // TODO: Move to SqlMetadataConnector
+  @Override
+  public void createTableDefnTable()
+  {
+    if (!metastoreManager.createTables()) {
+      return;
+    }
+    connector.createTable(
+        tableName,
+        ImmutableList.of(
+            StringUtils.format(
+                "CREATE TABLE %s (\n"

Review Comment:
   I think it's better to extract the create table statement here as a static 
constant and put it at the beginning of any other string constant of SQL 
template. Why? Because when I first look at above SQL string template, my first 
thought is what's the schema of the table and where is it?



##########
extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/http/CatalogListenerResource.java:
##########
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.http;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.jaxrs.smile.SmileMediaTypes;
+import org.apache.druid.catalog.model.TableMetadata;
+import org.apache.druid.catalog.model.TableSpec;
+import org.apache.druid.catalog.sync.CatalogUpdateNotifier;
+import org.apache.druid.catalog.sync.MetadataCatalog.CatalogListener;
+import org.apache.druid.guice.annotations.Json;
+import org.apache.druid.guice.annotations.Smile;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.server.security.Access;
+import org.apache.druid.server.security.Action;
+import org.apache.druid.server.security.AuthorizationUtils;
+import org.apache.druid.server.security.AuthorizerMapper;
+import org.apache.druid.server.security.Resource;
+import org.apache.druid.server.security.ResourceAction;
+import org.apache.druid.server.security.ResourceType;
+
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+@Path(CatalogListenerResource.BASE_URL)
+public class CatalogListenerResource
+{
+  public static final String BASE_URL = "/druid/broker/v1/catalog";
+  public static final String SYNC_URL = "/sync";
+
+  private final CatalogListener listener;
+  private final AuthorizerMapper authorizerMapper;
+  private final ObjectMapper smileMapper;
+  private final ObjectMapper jsonMapper;
+
+  @Inject
+  public CatalogListenerResource(
+      final CatalogListener listener,
+      @Smile final ObjectMapper smileMapper,
+      @Json final ObjectMapper jsonMapper,
+      final AuthorizerMapper authorizerMapper)
+  {
+    this.listener = listener;
+    this.authorizerMapper = authorizerMapper;
+    this.smileMapper = smileMapper;
+    this.jsonMapper = jsonMapper;
+  }
+
+  @POST
+  @Path(SYNC_URL)
+  @Consumes({MediaType.APPLICATION_JSON, 
SmileMediaTypes.APPLICATION_JACKSON_SMILE})

Review Comment:
   Could you explain why the SMILE encoding is supported for this endpoint?



##########
extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/storage/sql/SQLCatalogManager.java:
##########
@@ -0,0 +1,578 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.storage.sql;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.inject.Inject;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.TableMetadata;
+import org.apache.druid.catalog.model.TableSpec;
+import org.apache.druid.catalog.storage.MetastoreManager;
+import org.apache.druid.guice.ManageLifecycle;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
+import org.apache.druid.metadata.SQLMetadataConnector;
+import org.skife.jdbi.v2.Handle;
+import org.skife.jdbi.v2.IDBI;
+import org.skife.jdbi.v2.Query;
+import org.skife.jdbi.v2.ResultIterator;
+import org.skife.jdbi.v2.Update;
+import org.skife.jdbi.v2.exceptions.CallbackFailedException;
+import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;
+import org.skife.jdbi.v2.tweak.HandleCallback;
+
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.function.Function;
+
+@ManageLifecycle
+public class SQLCatalogManager implements CatalogManager
+{
+  public static final String TABLES_TABLE = "tableDefs";
+
+  private static final String INSERT_TABLE =
+      "INSERT INTO %s\n" +
+      "  (schemaName, name, creationTime, updateTime, state, payload)\n" +
+      "  VALUES(:schemaName, :name, :creationTime, :updateTime, :state, 
:payload)";
+
+  private static final String UPDATE_HEAD =
+      "UPDATE %s\n SET\n";
+
+  private static final String WHERE_TABLE_ID =
+      "WHERE schemaName = :schemaName\n" +
+      "  AND name = :name\n";
+
+  private static final String SAFETY_CHECK =
+      "  AND updateTime = :oldVersion";
+
+  private static final String UPDATE_DEFN_UNSAFE =
+      UPDATE_HEAD +
+      "  payload = :payload,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String UPDATE_DEFN_SAFE =
+      UPDATE_DEFN_UNSAFE +
+      SAFETY_CHECK;
+
+  private static final String UPDATE_STATE =
+      UPDATE_HEAD +
+      "  state = :state,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_TABLE =
+      "SELECT creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_PAYLOAD =
+      "SELECT state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_ALL_TABLES =
+      "SELECT schemaName, name\n" +
+      "FROM %s\n" +
+      "ORDER BY schemaName, name";
+
+  private static final String SELECT_TABLES_IN_SCHEMA =
+      "SELECT name\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String SELECT_TABLE_DETAILS_IN_SCHEMA =
+      "SELECT name, creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String DELETE_TABLE =
+      "DELETE FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private final MetastoreManager metastoreManager;
+  private final SQLMetadataConnector connector;
+  private final ObjectMapper jsonMapper;
+  private final IDBI dbi;
+  private final String tableName;
+  private final Deque<Listener> listeners = new ConcurrentLinkedDeque<>();
+
+  @Inject
+  public SQLCatalogManager(MetastoreManager metastoreManager)
+  {
+    if (!metastoreManager.isSql()) {
+      throw new ISE("SQLCatalogManager only works with SQL based metadata 
store at this time");
+    }
+    this.metastoreManager = metastoreManager;
+    this.connector = metastoreManager.sqlConnector();
+    this.dbi = connector.getDBI();
+    this.jsonMapper = metastoreManager.jsonMapper();
+    this.tableName = getTableDefnTable();
+  }
+
+  @Override
+  @LifecycleStart
+  public void start()
+  {
+    createTableDefnTable();
+  }
+
+  @Override
+  public void stop()
+  {
+  }
+
+  // Mimics what MetadataStorageTablesConfig should do.
+  public String getTableDefnTable()
+  {
+    final String base = metastoreManager.tablesConfig().getBase();
+    if (Strings.isNullOrEmpty(base)) {
+      return TABLES_TABLE;
+    } else {
+      return StringUtils.format("%s_%s", base, TABLES_TABLE);
+    }
+  }
+
+  // TODO: Move to SqlMetadataConnector
+  @Override
+  public void createTableDefnTable()
+  {
+    if (!metastoreManager.createTables()) {
+      return;
+    }
+    connector.createTable(
+        tableName,
+        ImmutableList.of(
+            StringUtils.format(
+                "CREATE TABLE %s (\n"
+                + "  schemaName VARCHAR(255) NOT NULL,\n"
+                + "  name VARCHAR(255) NOT NULL,\n"
+                + "  creationTime BIGINT NOT NULL,\n"
+                + "  updateTime BIGINT NOT NULL,\n"
+                + "  state CHAR(1) NOT NULL,\n"
+                + "  payload %s,\n"
+                + "  PRIMARY KEY(schemaName, name)\n"
+                + ")",
+                tableName,
+                connector.getPayloadType())));
+  }
+
+  @Override
+  public long create(TableMetadata table) throws DuplicateKeyException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws DuplicateKeyException
+            {
+              long updateTime = System.currentTimeMillis();
+              Update stmt = handle.createStatement(
+                  StringUtils.format(INSERT_TABLE, tableName)
+              )
+                  .bind("schemaName", table.id().schema())
+                  .bind("name", table.id().name())
+                  .bind("creationTime", updateTime)
+                  .bind("updateTime", updateTime)
+                  .bind("state", TableMetadata.TableState.ACTIVE.code())
+                  .bind("payload", table.spec().toBytes(jsonMapper));
+              try {
+                stmt.execute();
+              }
+              catch (UnableToExecuteStatementException e) {
+                if (DbUtils.isDuplicateRecordException(e)) {
+                  throw new DuplicateKeyException(
+                        "Tried to insert a duplicate table: " + 
table.sqlName(),
+                        e);
+                } else {
+                  throw e;
+                }
+              }
+              sendAddition(table, updateTime);
+              return updateTime;
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof DuplicateKeyException) {
+        throw (DuplicateKeyException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  @Override
+  public TableMetadata read(TableId id)
+  {
+    return dbi.withHandle(
+        new HandleCallback<TableMetadata>()
+        {
+          @Override
+          public TableMetadata withHandle(Handle handle)
+          {
+            Query<Map<String, Object>> query = handle.createQuery(
+                StringUtils.format(SELECT_TABLE, tableName)
+            )
+                .setFetchSize(connector.getStreamingFetchSize())
+                .bind("schemaName", id.schema())
+                .bind("name", id.name());
+            final ResultIterator<TableMetadata> resultIterator =
+                query.map((index, r, ctx) ->
+                  new TableMetadata(
+                      id,
+                      r.getLong(1),
+                      r.getLong(2),
+                      TableMetadata.TableState.fromCode(r.getString(3)),
+                      TableSpec.fromBytes(jsonMapper, r.getBytes(4))
+                  ))
+                .iterator();
+            if (resultIterator.hasNext()) {
+              return resultIterator.next();
+            }
+            return null;
+          }
+        }
+    );
+  }
+
+  @Override
+  public long update(TableMetadata table, long oldVersion) throws 
OutOfDateException, NotFoundException
+  {
+    if (oldVersion == 0) {
+      return updateUnsafe(table.id(), table.spec());
+    } else {
+      return updateSafe(table.id(), table.spec(), oldVersion);
+    }
+  }
+
+  private long updateSafe(TableId id, TableSpec defn, long oldVersion) throws 
OutOfDateException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws OutOfDateException
+            {
+              long updateTime = System.currentTimeMillis();
+              int updateCount = handle.createStatement(
+                  StringUtils.format(UPDATE_DEFN_SAFE, tableName))
+                  .bind("schemaName", id.schema())
+                  .bind("name", id.name())
+                  .bind("payload", defn.toBytes(jsonMapper))
+                  .bind("updateTime", updateTime)
+                  .bind("oldVersion", oldVersion)
+                  .execute();
+              if (updateCount == 0) {
+                throw new OutOfDateException(
+                    StringUtils.format(
+                        "Table %s: not found or update version does not match 
DB version",
+                        id.sqlName()));
+              }
+              sendUpdate(id);
+              return updateTime;
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof OutOfDateException) {
+        throw (OutOfDateException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  private long updateUnsafe(TableId id, TableSpec defn) throws 
NotFoundException

Review Comment:
   Don't understand why there is such a method that updating the record without 
checking the record version.



##########
extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/storage/sql/SQLCatalogManager.java:
##########
@@ -0,0 +1,578 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.storage.sql;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.inject.Inject;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.TableMetadata;
+import org.apache.druid.catalog.model.TableSpec;
+import org.apache.druid.catalog.storage.MetastoreManager;
+import org.apache.druid.guice.ManageLifecycle;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
+import org.apache.druid.metadata.SQLMetadataConnector;
+import org.skife.jdbi.v2.Handle;
+import org.skife.jdbi.v2.IDBI;
+import org.skife.jdbi.v2.Query;
+import org.skife.jdbi.v2.ResultIterator;
+import org.skife.jdbi.v2.Update;
+import org.skife.jdbi.v2.exceptions.CallbackFailedException;
+import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;
+import org.skife.jdbi.v2.tweak.HandleCallback;
+
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.function.Function;
+
+@ManageLifecycle
+public class SQLCatalogManager implements CatalogManager
+{
+  public static final String TABLES_TABLE = "tableDefs";
+
+  private static final String INSERT_TABLE =
+      "INSERT INTO %s\n" +
+      "  (schemaName, name, creationTime, updateTime, state, payload)\n" +
+      "  VALUES(:schemaName, :name, :creationTime, :updateTime, :state, 
:payload)";
+
+  private static final String UPDATE_HEAD =
+      "UPDATE %s\n SET\n";
+
+  private static final String WHERE_TABLE_ID =
+      "WHERE schemaName = :schemaName\n" +
+      "  AND name = :name\n";
+
+  private static final String SAFETY_CHECK =
+      "  AND updateTime = :oldVersion";
+
+  private static final String UPDATE_DEFN_UNSAFE =
+      UPDATE_HEAD +
+      "  payload = :payload,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String UPDATE_DEFN_SAFE =
+      UPDATE_DEFN_UNSAFE +
+      SAFETY_CHECK;
+
+  private static final String UPDATE_STATE =
+      UPDATE_HEAD +
+      "  state = :state,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_TABLE =
+      "SELECT creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_PAYLOAD =
+      "SELECT state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_ALL_TABLES =
+      "SELECT schemaName, name\n" +
+      "FROM %s\n" +
+      "ORDER BY schemaName, name";
+
+  private static final String SELECT_TABLES_IN_SCHEMA =
+      "SELECT name\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String SELECT_TABLE_DETAILS_IN_SCHEMA =
+      "SELECT name, creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String DELETE_TABLE =
+      "DELETE FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private final MetastoreManager metastoreManager;
+  private final SQLMetadataConnector connector;
+  private final ObjectMapper jsonMapper;
+  private final IDBI dbi;
+  private final String tableName;
+  private final Deque<Listener> listeners = new ConcurrentLinkedDeque<>();
+
+  @Inject
+  public SQLCatalogManager(MetastoreManager metastoreManager)
+  {
+    if (!metastoreManager.isSql()) {
+      throw new ISE("SQLCatalogManager only works with SQL based metadata 
store at this time");
+    }
+    this.metastoreManager = metastoreManager;
+    this.connector = metastoreManager.sqlConnector();
+    this.dbi = connector.getDBI();
+    this.jsonMapper = metastoreManager.jsonMapper();
+    this.tableName = getTableDefnTable();
+  }
+
+  @Override
+  @LifecycleStart
+  public void start()
+  {
+    createTableDefnTable();
+  }
+
+  @Override
+  public void stop()
+  {
+  }
+
+  // Mimics what MetadataStorageTablesConfig should do.
+  public String getTableDefnTable()
+  {
+    final String base = metastoreManager.tablesConfig().getBase();
+    if (Strings.isNullOrEmpty(base)) {
+      return TABLES_TABLE;
+    } else {
+      return StringUtils.format("%s_%s", base, TABLES_TABLE);
+    }
+  }
+
+  // TODO: Move to SqlMetadataConnector
+  @Override
+  public void createTableDefnTable()
+  {
+    if (!metastoreManager.createTables()) {
+      return;
+    }
+    connector.createTable(
+        tableName,
+        ImmutableList.of(
+            StringUtils.format(
+                "CREATE TABLE %s (\n"
+                + "  schemaName VARCHAR(255) NOT NULL,\n"
+                + "  name VARCHAR(255) NOT NULL,\n"
+                + "  creationTime BIGINT NOT NULL,\n"
+                + "  updateTime BIGINT NOT NULL,\n"
+                + "  state CHAR(1) NOT NULL,\n"
+                + "  payload %s,\n"
+                + "  PRIMARY KEY(schemaName, name)\n"
+                + ")",
+                tableName,
+                connector.getPayloadType())));
+  }
+
+  @Override
+  public long create(TableMetadata table) throws DuplicateKeyException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws DuplicateKeyException
+            {
+              long updateTime = System.currentTimeMillis();
+              Update stmt = handle.createStatement(
+                  StringUtils.format(INSERT_TABLE, tableName)
+              )
+                  .bind("schemaName", table.id().schema())
+                  .bind("name", table.id().name())
+                  .bind("creationTime", updateTime)
+                  .bind("updateTime", updateTime)
+                  .bind("state", TableMetadata.TableState.ACTIVE.code())
+                  .bind("payload", table.spec().toBytes(jsonMapper));
+              try {
+                stmt.execute();
+              }
+              catch (UnableToExecuteStatementException e) {
+                if (DbUtils.isDuplicateRecordException(e)) {
+                  throw new DuplicateKeyException(
+                        "Tried to insert a duplicate table: " + 
table.sqlName(),
+                        e);
+                } else {
+                  throw e;
+                }
+              }
+              sendAddition(table, updateTime);
+              return updateTime;
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof DuplicateKeyException) {
+        throw (DuplicateKeyException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  @Override
+  public TableMetadata read(TableId id)
+  {
+    return dbi.withHandle(
+        new HandleCallback<TableMetadata>()
+        {
+          @Override
+          public TableMetadata withHandle(Handle handle)
+          {
+            Query<Map<String, Object>> query = handle.createQuery(
+                StringUtils.format(SELECT_TABLE, tableName)
+            )
+                .setFetchSize(connector.getStreamingFetchSize())
+                .bind("schemaName", id.schema())
+                .bind("name", id.name());
+            final ResultIterator<TableMetadata> resultIterator =
+                query.map((index, r, ctx) ->
+                  new TableMetadata(
+                      id,
+                      r.getLong(1),
+                      r.getLong(2),
+                      TableMetadata.TableState.fromCode(r.getString(3)),
+                      TableSpec.fromBytes(jsonMapper, r.getBytes(4))
+                  ))
+                .iterator();
+            if (resultIterator.hasNext()) {
+              return resultIterator.next();
+            }
+            return null;
+          }
+        }
+    );
+  }
+
+  @Override
+  public long update(TableMetadata table, long oldVersion) throws 
OutOfDateException, NotFoundException
+  {
+    if (oldVersion == 0) {
+      return updateUnsafe(table.id(), table.spec());
+    } else {
+      return updateSafe(table.id(), table.spec(), oldVersion);
+    }
+  }
+
+  private long updateSafe(TableId id, TableSpec defn, long oldVersion) throws 
OutOfDateException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws OutOfDateException
+            {
+              long updateTime = System.currentTimeMillis();
+              int updateCount = handle.createStatement(
+                  StringUtils.format(UPDATE_DEFN_SAFE, tableName))
+                  .bind("schemaName", id.schema())
+                  .bind("name", id.name())
+                  .bind("payload", defn.toBytes(jsonMapper))
+                  .bind("updateTime", updateTime)
+                  .bind("oldVersion", oldVersion)
+                  .execute();
+              if (updateCount == 0) {
+                throw new OutOfDateException(
+                    StringUtils.format(
+                        "Table %s: not found or update version does not match 
DB version",
+                        id.sqlName()));
+              }
+              sendUpdate(id);
+              return updateTime;
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof OutOfDateException) {
+        throw (OutOfDateException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  private long updateUnsafe(TableId id, TableSpec defn) throws 
NotFoundException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws NotFoundException
+            {
+              long updateTime = System.currentTimeMillis();
+              int updateCount = handle.createStatement(
+                  StringUtils.format(UPDATE_DEFN_UNSAFE, tableName))
+                  .bind("schemaName", id.schema())
+                  .bind("name", id.name())
+                  .bind("payload", defn.toBytes(jsonMapper))
+                  .bind("updateTime", updateTime)
+                  .execute();
+              if (updateCount == 0) {
+                throw new NotFoundException(
+                    StringUtils.format("Table %s: not found", id.sqlName())
+                );
+              }
+              sendUpdate(id);
+              return updateTime;
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof NotFoundException) {
+        throw (NotFoundException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  @Override
+  public long updatePayload(TableId id, Function<TableSpec, TableSpec> 
transform) throws NotFoundException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws NotFoundException
+            {
+              handle.begin();
+              try {
+                Query<Map<String, Object>> query = handle.createQuery(
+                    StringUtils.format(SELECT_PAYLOAD, tableName)
+                )
+                    .setFetchSize(connector.getStreamingFetchSize())
+                    .bind("schemaName", id.schema())
+                    .bind("name", id.name());
+
+                final ResultIterator<TableMetadata> resultIterator =
+                    query.map((index, r, ctx) ->
+                      new TableMetadata(
+                          id,
+                          0,
+                          0,
+                          TableMetadata.TableState.fromCode(r.getString(1)),
+                          TableSpec.fromBytes(jsonMapper, r.getBytes(2))
+                      ))
+                    .iterator();
+                TableMetadata table;
+                if (resultIterator.hasNext()) {
+                  table = resultIterator.next();
+                } else {
+                  handle.rollback();
+                  throw new NotFoundException(
+                      StringUtils.format("Table %s: not found", id.sqlName())
+                  );
+                }
+                if (table.state() != TableMetadata.TableState.ACTIVE) {
+                  throw new ISE("Table is in state [%s] and cannot be 
updated", table.state());
+                }
+                TableSpec revised = transform.apply(table.spec());
+                long updateTime = System.currentTimeMillis();
+                int updateCount = handle.createStatement(
+                    StringUtils.format(UPDATE_DEFN_UNSAFE, tableName))
+                    .bind("schemaName", id.schema())
+                    .bind("name", id.name())
+                    .bind("payload", revised.toBytes(jsonMapper))
+                    .bind("updateTime", updateTime)
+                    .execute();
+                if (updateCount == 0) {
+                  // Should never occur because we're holding a lock.
+                  throw new ISE("Table %s: not found", id.sqlName());
+                }
+                handle.commit();
+                sendUpdate(id);
+                return updateTime;
+              }
+              catch (RuntimeException e) {
+                handle.rollback();
+                throw e;
+              }
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof NotFoundException) {
+        throw (NotFoundException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  @Override
+  public long markDeleting(TableId id)

Review Comment:
   What the lifecycle of a table in catalog? I mean, there's a method to allow 
us to mark a table as DELETING, but no other methods to turn state from 
`DELETING` to `ACTIVE`.



##########
server/src/main/java/org/apache/druid/catalog/model/Properties.java:
##########
@@ -0,0 +1,305 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.model;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Preconditions;
+import org.apache.druid.java.util.common.IAE;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.granularity.PeriodGranularity;
+import org.joda.time.Period;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Definition of a top-level property in a catalog object.
+ * Provides a set of typical property definitions. Others can be
+ * created case-by-case.
+ * <p>
+ * Property definitions define the property name, validate the value,
+ * and merge updates. Properties have a type: but the type is implicit
+ * via the validation, as is needed when the type is actually a map
+ * which represents a Java object, or when the value is a list.
+ */
+public interface Properties

Review Comment:
   Can we give it another name? Because there's already `java.util.Properties`, 
the same name interface might be confusing



##########
extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/storage/HideColumns.java:
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.storage;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+
+public class HideColumns
+{
+  @JsonProperty
+  public final List<String> hide;
+  @JsonProperty
+  public final List<String> unhide;
+
+  @JsonCreator
+  public HideColumns(
+      @JsonProperty("hide") @Nullable final List<String> hide,
+      @JsonProperty("unhide") @Nullable final List<String> unhide
+  )
+  {
+    this.hide = hide;
+    this.unhide = unhide;
+  }
+
+  @JsonIgnore
+  public boolean isEmpty()
+  {
+    return (hide == null || hide.isEmpty())
+        && (unhide == null || unhide.isEmpty());
+  }
+
+  public List<String> perform(List<String> hiddenColumns)

Review Comment:
   Could you add some javadoc to brief what this function does? Currently I 
have to read the implementation to know its intension because the method name 
is also too generic.



##########
server/src/main/java/org/apache/druid/catalog/model/SchemaRegistryImpl.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.model;
+
+import org.apache.druid.catalog.model.table.AbstractDatasourceDefn;
+import org.apache.druid.catalog.model.table.ExternalTableDefn;
+import org.apache.druid.server.security.ResourceType;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ * Hard-coded schema registry that knows about the well-known, and
+ * a few obscure, Druid schemas. Does not allow for user-defined
+ * schemas, which the rest of Druid would not be able to support.
+ */
+public class SchemaRegistryImpl implements SchemaRegistry
+{
+  // Mimics the definition in ExternalOperatorConvertion
+  // TODO: Change this when ExternalOperatorConvertion changes
+  private String EXTERNAL_RESOURCE = "EXTERNAL";
+
+  public static class SchemaDefnImpl implements SchemaSpec
+  {
+    private final String name;
+    private final String resource;
+    private final Set<String> accepts;
+
+    public SchemaDefnImpl(
+        String name,
+        String resource,
+        Set<String> accepts
+    )
+    {
+      this.name = name;
+      this.resource = resource;
+      this.accepts = accepts;
+    }
+
+    @Override
+    public String name()
+    {
+      return name;
+    }
+
+    @Override
+    public String securityResource()
+    {
+      return resource;
+    }
+
+    @Override
+    public boolean writable()
+    {
+      return accepts != null && !accepts.isEmpty();
+    }
+
+    @Override
+    public boolean accepts(String tableType)
+    {
+      if (accepts == null) {
+        return false;
+      }
+      return accepts.contains(tableType);
+    }
+  }
+
+  private final Map<String, SchemaSpec> builtIns;
+
+  public SchemaRegistryImpl()
+  {
+    builtIns = new HashMap<>();
+    register(new SchemaDefnImpl(
+        TableId.DRUID_SCHEMA,
+        ResourceType.DATASOURCE,
+        AbstractDatasourceDefn.tableTypes()
+    ));
+    register(new SchemaDefnImpl(
+        TableId.LOOKUP_SCHEMA,
+        ResourceType.CONFIG,
+        null // TODO
+    ));
+    register(new SchemaDefnImpl(
+        TableId.CATALOG_SCHEMA,
+        ResourceType.SYSTEM_TABLE,
+        null
+    ));
+    register(new SchemaDefnImpl(
+        TableId.SYSTEM_SCHEMA,
+        ResourceType.SYSTEM_TABLE,
+        null
+    ));
+    register(new SchemaDefnImpl(
+        TableId.EXTERNAL_SCHEMA,
+        EXTERNAL_RESOURCE,
+        ExternalTableDefn.tableTypes()
+    ));
+    register(new SchemaDefnImpl(
+        TableId.VIEW_SCHEMA,
+        ResourceType.VIEW,
+        null // TODO

Review Comment:
   and here



##########
extensions-core/druid-catalog/pom.xml:
##########
@@ -0,0 +1,328 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements.  See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership.  The ASF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License.  You may obtain a copy of the License at
+  ~
+  ~   http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied.  See the License for the
+  ~ specific language governing permissions and limitations
+  ~ under the License.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>org.apache.druid.extensions</groupId>
+    <artifactId>druid-catalog</artifactId>
+    <name>druid-catalog</name>
+    <description>Druid Catalog</description>
+
+    <parent>
+        <groupId>org.apache.druid</groupId>
+        <artifactId>druid</artifactId>
+        <version>25.0.0-SNAPSHOT</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-core</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-processing</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-server</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-indexing-service</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-sql</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-services</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.inject</groupId>
+            <artifactId>guice</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.inject.extensions</groupId>
+            <artifactId>guice-multibindings</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.opencsv</groupId>
+            <artifactId>opencsv</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-databind</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-annotations</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.validation</groupId>
+            <artifactId>validation-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.code.findbugs</groupId>
+            <artifactId>jsr305</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>jakarta.inject</groupId>
+            <artifactId>jakarta.inject-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>joda-time</groupId>
+            <artifactId>joda-time</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.netty</groupId>
+            <artifactId>netty</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.calcite</groupId>
+            <artifactId>calcite-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+               <dependency>
+                       <groupId>javax.inject</groupId>
+                       <artifactId>javax.inject</artifactId>
+                       <version>1</version>
+                       <scope>provided</scope>
+               </dependency>
+               <dependency>
+                   <groupId>org.apache.curator</groupId>
+                   <artifactId>curator-client</artifactId>
+                   <scope>provided</scope>
+               </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.dataformat</groupId>
+            <artifactId>jackson-dataformat-smile</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jdbi</groupId>
+            <artifactId>jdbi</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.jaxrs</groupId>
+            <artifactId>jackson-jaxrs-smile-provider</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.ws.rs</groupId>
+            <artifactId>jsr311-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>javax.servlet-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-server</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.errorprone</groupId>
+            <artifactId>error_prone_annotations</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.lz4</groupId>
+            <artifactId>lz4-java</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.datasketches</groupId>
+            <artifactId>datasketches-java</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.datasketches</groupId>
+            <artifactId>datasketches-memory</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>it.unimi.dsi</groupId>
+            <artifactId>fastutil-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <scope>provided</scope>
+        </dependency>
+
+        <!-- Tests -->
+        <dependency>
+            <groupId>org.easymock</groupId>
+            <artifactId>easymock</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.hamcrest</groupId>
+            <artifactId>hamcrest-all</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.hamcrest</groupId>
+            <artifactId>hamcrest-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>nl.jqno.equalsverifier</groupId>
+            <artifactId>equalsverifier</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-core</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>test</scope>
+            <type>test-jar</type>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-processing</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>test</scope>
+            <type>test-jar</type>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-server</artifactId>
+            <version>${project.parent.version}</version>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-sql</artifactId>
+            <version>${project.parent.version}</version>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-hll</artifactId>
+            <version>${project.parent.version}</version>
+            <!-- Used in tests. Marked as scope "provided" instead of "test", 
because scope "test" prevents
+                 running using this extension's classpath in an IDE. -->
+            <scope>provided</scope>
+        </dependency>
+
+    </dependencies>
+    <build>
+        <plugins>

Review Comment:
   Why do we need an empty `plugins` element?



##########
server/src/main/java/org/apache/druid/catalog/model/CatalogUtils.java:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.model;
+
+import com.google.common.base.Strings;
+import org.apache.druid.java.util.common.IAE;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.granularity.Granularities;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.java.util.common.granularity.PeriodGranularity;
+import org.joda.time.Period;
+
+import javax.annotation.Nullable;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class CatalogUtils
+{
+  public static List<String> columnNames(List<ColumnSpec> columns)
+  {
+    return columns
+           .stream()
+           .map(col -> col.name())
+           .collect(Collectors.toList());
+  }
+
+  /**
+   * Convert a catalog granularity string to the Druid form. Catalog 
granularities
+   * are either the usual descriptive strings (in any case), or an ISO period.
+   * For the odd interval, the interval name is also accepted (for the other
+   * intervals, the interval name is the descriptive string).
+   */
+  public static Granularity asDruidGranularity(String value)
+  {
+    if (Strings.isNullOrEmpty(value)) {
+      return Granularities.ALL;
+    }
+    try {
+      return new PeriodGranularity(new Period(value), null, null);
+    }
+    catch (IllegalArgumentException e) {
+      throw new IAE(StringUtils.format("%s is an invalid period string", 
value));
+    }
+  }
+
+  /**
+   * {@code String}-to-{@code List<String>} conversion. The string can contain 
zero items,
+   * one items, or a list. The list items are separated by a comma and optional
+   * whitespace.
+   */
+  public static List<String> stringToList(String value)

Review Comment:
   maybe `splitToList` is better?



##########
extensions-core/druid-catalog/pom.xml:
##########
@@ -0,0 +1,328 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements.  See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership.  The ASF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License.  You may obtain a copy of the License at
+  ~
+  ~   http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied.  See the License for the
+  ~ specific language governing permissions and limitations
+  ~ under the License.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>org.apache.druid.extensions</groupId>
+    <artifactId>druid-catalog</artifactId>
+    <name>druid-catalog</name>
+    <description>Druid Catalog</description>
+
+    <parent>
+        <groupId>org.apache.druid</groupId>
+        <artifactId>druid</artifactId>
+        <version>25.0.0-SNAPSHOT</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-core</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-processing</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-server</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-indexing-service</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-sql</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-services</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.inject</groupId>
+            <artifactId>guice</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.inject.extensions</groupId>
+            <artifactId>guice-multibindings</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.opencsv</groupId>
+            <artifactId>opencsv</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-databind</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-annotations</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.validation</groupId>
+            <artifactId>validation-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.code.findbugs</groupId>
+            <artifactId>jsr305</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>jakarta.inject</groupId>
+            <artifactId>jakarta.inject-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>joda-time</groupId>
+            <artifactId>joda-time</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.netty</groupId>
+            <artifactId>netty</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.calcite</groupId>
+            <artifactId>calcite-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+               <dependency>
+                       <groupId>javax.inject</groupId>
+                       <artifactId>javax.inject</artifactId>
+                       <version>1</version>
+                       <scope>provided</scope>
+               </dependency>
+               <dependency>
+                   <groupId>org.apache.curator</groupId>
+                   <artifactId>curator-client</artifactId>
+                   <scope>provided</scope>
+               </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.dataformat</groupId>
+            <artifactId>jackson-dataformat-smile</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jdbi</groupId>
+            <artifactId>jdbi</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.jaxrs</groupId>
+            <artifactId>jackson-jaxrs-smile-provider</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.ws.rs</groupId>
+            <artifactId>jsr311-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>javax.servlet-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-server</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.errorprone</groupId>
+            <artifactId>error_prone_annotations</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.lz4</groupId>
+            <artifactId>lz4-java</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.datasketches</groupId>
+            <artifactId>datasketches-java</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.datasketches</groupId>
+            <artifactId>datasketches-memory</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>it.unimi.dsi</groupId>
+            <artifactId>fastutil-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <scope>provided</scope>
+        </dependency>
+
+        <!-- Tests -->
+        <dependency>
+            <groupId>org.easymock</groupId>
+            <artifactId>easymock</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.hamcrest</groupId>
+            <artifactId>hamcrest-all</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.hamcrest</groupId>
+            <artifactId>hamcrest-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>nl.jqno.equalsverifier</groupId>
+            <artifactId>equalsverifier</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-core</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>test</scope>
+            <type>test-jar</type>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-processing</artifactId>
+            <version>${project.parent.version}</version>
+            <scope>test</scope>
+            <type>test-jar</type>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-server</artifactId>
+            <version>${project.parent.version}</version>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-sql</artifactId>
+            <version>${project.parent.version}</version>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.druid</groupId>
+            <artifactId>druid-hll</artifactId>
+            <version>${project.parent.version}</version>
+            <!-- Used in tests. Marked as scope "provided" instead of "test", 
because scope "test" prevents
+                 running using this extension's classpath in an IDE. -->
+            <scope>provided</scope>
+        </dependency>
+
+    </dependencies>
+    <build>
+        <plugins>

Review Comment:
   Why do we need an empty `plugins` element?



##########
server/src/main/java/org/apache/druid/catalog/model/SchemaRegistryImpl.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.model;
+
+import org.apache.druid.catalog.model.table.AbstractDatasourceDefn;
+import org.apache.druid.catalog.model.table.ExternalTableDefn;
+import org.apache.druid.server.security.ResourceType;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ * Hard-coded schema registry that knows about the well-known, and
+ * a few obscure, Druid schemas. Does not allow for user-defined
+ * schemas, which the rest of Druid would not be able to support.
+ */
+public class SchemaRegistryImpl implements SchemaRegistry
+{
+  // Mimics the definition in ExternalOperatorConvertion
+  // TODO: Change this when ExternalOperatorConvertion changes
+  private String EXTERNAL_RESOURCE = "EXTERNAL";
+
+  public static class SchemaDefnImpl implements SchemaSpec
+  {
+    private final String name;
+    private final String resource;
+    private final Set<String> accepts;
+
+    public SchemaDefnImpl(
+        String name,
+        String resource,
+        Set<String> accepts
+    )
+    {
+      this.name = name;
+      this.resource = resource;
+      this.accepts = accepts;
+    }
+
+    @Override
+    public String name()
+    {
+      return name;
+    }
+
+    @Override
+    public String securityResource()
+    {
+      return resource;
+    }
+
+    @Override
+    public boolean writable()
+    {
+      return accepts != null && !accepts.isEmpty();
+    }
+
+    @Override
+    public boolean accepts(String tableType)
+    {
+      if (accepts == null) {
+        return false;
+      }
+      return accepts.contains(tableType);
+    }
+  }
+
+  private final Map<String, SchemaSpec> builtIns;
+
+  public SchemaRegistryImpl()
+  {
+    builtIns = new HashMap<>();
+    register(new SchemaDefnImpl(
+        TableId.DRUID_SCHEMA,
+        ResourceType.DATASOURCE,
+        AbstractDatasourceDefn.tableTypes()
+    ));
+    register(new SchemaDefnImpl(
+        TableId.LOOKUP_SCHEMA,
+        ResourceType.CONFIG,
+        null // TODO

Review Comment:
   What does the TODO here mean?



##########
extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/storage/sql/SQLCatalogManager.java:
##########
@@ -0,0 +1,578 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.storage.sql;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.inject.Inject;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.TableMetadata;
+import org.apache.druid.catalog.model.TableSpec;
+import org.apache.druid.catalog.storage.MetastoreManager;
+import org.apache.druid.guice.ManageLifecycle;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
+import org.apache.druid.metadata.SQLMetadataConnector;
+import org.skife.jdbi.v2.Handle;
+import org.skife.jdbi.v2.IDBI;
+import org.skife.jdbi.v2.Query;
+import org.skife.jdbi.v2.ResultIterator;
+import org.skife.jdbi.v2.Update;
+import org.skife.jdbi.v2.exceptions.CallbackFailedException;
+import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;
+import org.skife.jdbi.v2.tweak.HandleCallback;
+
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.function.Function;
+
+@ManageLifecycle
+public class SQLCatalogManager implements CatalogManager
+{
+  public static final String TABLES_TABLE = "tableDefs";
+
+  private static final String INSERT_TABLE =
+      "INSERT INTO %s\n" +
+      "  (schemaName, name, creationTime, updateTime, state, payload)\n" +
+      "  VALUES(:schemaName, :name, :creationTime, :updateTime, :state, 
:payload)";
+
+  private static final String UPDATE_HEAD =
+      "UPDATE %s\n SET\n";
+
+  private static final String WHERE_TABLE_ID =
+      "WHERE schemaName = :schemaName\n" +
+      "  AND name = :name\n";
+
+  private static final String SAFETY_CHECK =
+      "  AND updateTime = :oldVersion";
+
+  private static final String UPDATE_DEFN_UNSAFE =
+      UPDATE_HEAD +
+      "  payload = :payload,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String UPDATE_DEFN_SAFE =
+      UPDATE_DEFN_UNSAFE +
+      SAFETY_CHECK;

Review Comment:
   To be honestly, it's very hard to know how the SQL looks like even with the 
help of IDE.
   I think it's better to inline these statements in its method. Or If we want 
put SQLs together, we can inline these constants for each statement.



##########
extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/storage/sql/SQLCatalogManager.java:
##########
@@ -0,0 +1,578 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.storage.sql;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.inject.Inject;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.TableMetadata;
+import org.apache.druid.catalog.model.TableSpec;
+import org.apache.druid.catalog.storage.MetastoreManager;
+import org.apache.druid.guice.ManageLifecycle;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
+import org.apache.druid.metadata.SQLMetadataConnector;
+import org.skife.jdbi.v2.Handle;
+import org.skife.jdbi.v2.IDBI;
+import org.skife.jdbi.v2.Query;
+import org.skife.jdbi.v2.ResultIterator;
+import org.skife.jdbi.v2.Update;
+import org.skife.jdbi.v2.exceptions.CallbackFailedException;
+import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;
+import org.skife.jdbi.v2.tweak.HandleCallback;
+
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.function.Function;
+
+@ManageLifecycle
+public class SQLCatalogManager implements CatalogManager
+{
+  public static final String TABLES_TABLE = "tableDefs";
+
+  private static final String INSERT_TABLE =
+      "INSERT INTO %s\n" +
+      "  (schemaName, name, creationTime, updateTime, state, payload)\n" +
+      "  VALUES(:schemaName, :name, :creationTime, :updateTime, :state, 
:payload)";
+
+  private static final String UPDATE_HEAD =
+      "UPDATE %s\n SET\n";
+
+  private static final String WHERE_TABLE_ID =
+      "WHERE schemaName = :schemaName\n" +
+      "  AND name = :name\n";
+
+  private static final String SAFETY_CHECK =
+      "  AND updateTime = :oldVersion";
+
+  private static final String UPDATE_DEFN_UNSAFE =
+      UPDATE_HEAD +
+      "  payload = :payload,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String UPDATE_DEFN_SAFE =
+      UPDATE_DEFN_UNSAFE +
+      SAFETY_CHECK;
+
+  private static final String UPDATE_STATE =
+      UPDATE_HEAD +
+      "  state = :state,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_TABLE =
+      "SELECT creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_PAYLOAD =
+      "SELECT state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_ALL_TABLES =
+      "SELECT schemaName, name\n" +
+      "FROM %s\n" +
+      "ORDER BY schemaName, name";
+
+  private static final String SELECT_TABLES_IN_SCHEMA =
+      "SELECT name\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String SELECT_TABLE_DETAILS_IN_SCHEMA =
+      "SELECT name, creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String DELETE_TABLE =
+      "DELETE FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private final MetastoreManager metastoreManager;
+  private final SQLMetadataConnector connector;
+  private final ObjectMapper jsonMapper;
+  private final IDBI dbi;
+  private final String tableName;
+  private final Deque<Listener> listeners = new ConcurrentLinkedDeque<>();
+
+  @Inject
+  public SQLCatalogManager(MetastoreManager metastoreManager)
+  {
+    if (!metastoreManager.isSql()) {
+      throw new ISE("SQLCatalogManager only works with SQL based metadata 
store at this time");
+    }
+    this.metastoreManager = metastoreManager;
+    this.connector = metastoreManager.sqlConnector();
+    this.dbi = connector.getDBI();
+    this.jsonMapper = metastoreManager.jsonMapper();
+    this.tableName = getTableDefnTable();
+  }
+
+  @Override
+  @LifecycleStart
+  public void start()
+  {
+    createTableDefnTable();
+  }
+
+  @Override
+  public void stop()
+  {
+  }
+
+  // Mimics what MetadataStorageTablesConfig should do.
+  public String getTableDefnTable()
+  {
+    final String base = metastoreManager.tablesConfig().getBase();
+    if (Strings.isNullOrEmpty(base)) {
+      return TABLES_TABLE;
+    } else {
+      return StringUtils.format("%s_%s", base, TABLES_TABLE);
+    }
+  }
+
+  // TODO: Move to SqlMetadataConnector
+  @Override
+  public void createTableDefnTable()
+  {
+    if (!metastoreManager.createTables()) {
+      return;
+    }
+    connector.createTable(
+        tableName,
+        ImmutableList.of(
+            StringUtils.format(
+                "CREATE TABLE %s (\n"
+                + "  schemaName VARCHAR(255) NOT NULL,\n"
+                + "  name VARCHAR(255) NOT NULL,\n"
+                + "  creationTime BIGINT NOT NULL,\n"
+                + "  updateTime BIGINT NOT NULL,\n"
+                + "  state CHAR(1) NOT NULL,\n"
+                + "  payload %s,\n"
+                + "  PRIMARY KEY(schemaName, name)\n"
+                + ")",
+                tableName,
+                connector.getPayloadType())));
+  }
+
+  @Override
+  public long create(TableMetadata table) throws DuplicateKeyException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws DuplicateKeyException
+            {
+              long updateTime = System.currentTimeMillis();
+              Update stmt = handle.createStatement(
+                  StringUtils.format(INSERT_TABLE, tableName)
+              )
+                  .bind("schemaName", table.id().schema())
+                  .bind("name", table.id().name())
+                  .bind("creationTime", updateTime)
+                  .bind("updateTime", updateTime)
+                  .bind("state", TableMetadata.TableState.ACTIVE.code())
+                  .bind("payload", table.spec().toBytes(jsonMapper));
+              try {
+                stmt.execute();
+              }
+              catch (UnableToExecuteStatementException e) {
+                if (DbUtils.isDuplicateRecordException(e)) {
+                  throw new DuplicateKeyException(
+                        "Tried to insert a duplicate table: " + 
table.sqlName(),
+                        e);
+                } else {
+                  throw e;
+                }
+              }
+              sendAddition(table, updateTime);
+              return updateTime;
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof DuplicateKeyException) {
+        throw (DuplicateKeyException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  @Override
+  public TableMetadata read(TableId id)
+  {
+    return dbi.withHandle(
+        new HandleCallback<TableMetadata>()
+        {
+          @Override
+          public TableMetadata withHandle(Handle handle)
+          {
+            Query<Map<String, Object>> query = handle.createQuery(
+                StringUtils.format(SELECT_TABLE, tableName)
+            )
+                .setFetchSize(connector.getStreamingFetchSize())
+                .bind("schemaName", id.schema())
+                .bind("name", id.name());
+            final ResultIterator<TableMetadata> resultIterator =
+                query.map((index, r, ctx) ->
+                  new TableMetadata(
+                      id,
+                      r.getLong(1),
+                      r.getLong(2),
+                      TableMetadata.TableState.fromCode(r.getString(3)),
+                      TableSpec.fromBytes(jsonMapper, r.getBytes(4))
+                  ))
+                .iterator();
+            if (resultIterator.hasNext()) {
+              return resultIterator.next();
+            }
+            return null;
+          }
+        }
+    );
+  }
+
+  @Override
+  public long update(TableMetadata table, long oldVersion) throws 
OutOfDateException, NotFoundException
+  {
+    if (oldVersion == 0) {
+      return updateUnsafe(table.id(), table.spec());
+    } else {
+      return updateSafe(table.id(), table.spec(), oldVersion);
+    }
+  }
+
+  private long updateSafe(TableId id, TableSpec defn, long oldVersion) throws 
OutOfDateException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws OutOfDateException
+            {
+              long updateTime = System.currentTimeMillis();
+              int updateCount = handle.createStatement(
+                  StringUtils.format(UPDATE_DEFN_SAFE, tableName))
+                  .bind("schemaName", id.schema())
+                  .bind("name", id.name())
+                  .bind("payload", defn.toBytes(jsonMapper))
+                  .bind("updateTime", updateTime)
+                  .bind("oldVersion", oldVersion)
+                  .execute();
+              if (updateCount == 0) {
+                throw new OutOfDateException(
+                    StringUtils.format(
+                        "Table %s: not found or update version does not match 
DB version",
+                        id.sqlName()));
+              }
+              sendUpdate(id);
+              return updateTime;
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof OutOfDateException) {
+        throw (OutOfDateException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  private long updateUnsafe(TableId id, TableSpec defn) throws 
NotFoundException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws NotFoundException
+            {
+              long updateTime = System.currentTimeMillis();
+              int updateCount = handle.createStatement(
+                  StringUtils.format(UPDATE_DEFN_UNSAFE, tableName))
+                  .bind("schemaName", id.schema())
+                  .bind("name", id.name())
+                  .bind("payload", defn.toBytes(jsonMapper))
+                  .bind("updateTime", updateTime)
+                  .execute();
+              if (updateCount == 0) {
+                throw new NotFoundException(
+                    StringUtils.format("Table %s: not found", id.sqlName())
+                );
+              }
+              sendUpdate(id);
+              return updateTime;
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof NotFoundException) {
+        throw (NotFoundException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  @Override
+  public long updatePayload(TableId id, Function<TableSpec, TableSpec> 
transform) throws NotFoundException
+  {
+    try {
+      return dbi.withHandle(
+          new HandleCallback<Long>()
+          {
+            @Override
+            public Long withHandle(Handle handle) throws NotFoundException
+            {
+              handle.begin();
+              try {
+                Query<Map<String, Object>> query = handle.createQuery(
+                    StringUtils.format(SELECT_PAYLOAD, tableName)
+                )
+                    .setFetchSize(connector.getStreamingFetchSize())
+                    .bind("schemaName", id.schema())
+                    .bind("name", id.name());
+
+                final ResultIterator<TableMetadata> resultIterator =
+                    query.map((index, r, ctx) ->
+                      new TableMetadata(
+                          id,
+                          0,
+                          0,
+                          TableMetadata.TableState.fromCode(r.getString(1)),
+                          TableSpec.fromBytes(jsonMapper, r.getBytes(2))
+                      ))
+                    .iterator();
+                TableMetadata table;
+                if (resultIterator.hasNext()) {
+                  table = resultIterator.next();
+                } else {
+                  handle.rollback();
+                  throw new NotFoundException(
+                      StringUtils.format("Table %s: not found", id.sqlName())
+                  );
+                }
+                if (table.state() != TableMetadata.TableState.ACTIVE) {
+                  throw new ISE("Table is in state [%s] and cannot be 
updated", table.state());
+                }
+                TableSpec revised = transform.apply(table.spec());
+                long updateTime = System.currentTimeMillis();
+                int updateCount = handle.createStatement(
+                    StringUtils.format(UPDATE_DEFN_UNSAFE, tableName))
+                    .bind("schemaName", id.schema())
+                    .bind("name", id.name())
+                    .bind("payload", revised.toBytes(jsonMapper))
+                    .bind("updateTime", updateTime)
+                    .execute();
+                if (updateCount == 0) {
+                  // Should never occur because we're holding a lock.
+                  throw new ISE("Table %s: not found", id.sqlName());
+                }
+                handle.commit();
+                sendUpdate(id);
+                return updateTime;
+              }
+              catch (RuntimeException e) {
+                handle.rollback();
+                throw e;
+              }
+            }
+          }
+      );
+    }
+    catch (CallbackFailedException e) {
+      if (e.getCause() instanceof NotFoundException) {
+        throw (NotFoundException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  @Override
+  public long markDeleting(TableId id)
+  {
+    return dbi.withHandle(
+        new HandleCallback<Long>()
+        {
+          @Override
+          public Long withHandle(Handle handle)
+          {
+            long updateTime = System.currentTimeMillis();
+            int updateCount = handle.createStatement(
+                StringUtils.format(UPDATE_STATE, tableName))
+                .bind("schemaName", id.schema())
+                .bind("name", id.name())
+                .bind("updateTime", updateTime)
+                .bind("state", TableMetadata.TableState.DELETING.code())
+                .execute();
+            sendDeletion(id);
+            return updateCount == 1 ? updateTime : 0;
+          }
+        }
+    );
+  }
+
+  @Override
+  public boolean delete(TableId id)
+  {
+    return dbi.withHandle(
+        new HandleCallback<Boolean>()
+        {
+          @Override
+          public Boolean withHandle(Handle handle)
+          {
+            int updateCount = handle.createStatement(
+                StringUtils.format(DELETE_TABLE, tableName))
+                .bind("schemaName", id.schema())
+                .bind("name", id.name())

Review Comment:
   So we can delete a table from catalog even its state if `ACTIVE`?



##########
extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/storage/sql/SQLCatalogManager.java:
##########
@@ -0,0 +1,578 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.catalog.storage.sql;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.inject.Inject;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.TableMetadata;
+import org.apache.druid.catalog.model.TableSpec;
+import org.apache.druid.catalog.storage.MetastoreManager;
+import org.apache.druid.guice.ManageLifecycle;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
+import org.apache.druid.metadata.SQLMetadataConnector;
+import org.skife.jdbi.v2.Handle;
+import org.skife.jdbi.v2.IDBI;
+import org.skife.jdbi.v2.Query;
+import org.skife.jdbi.v2.ResultIterator;
+import org.skife.jdbi.v2.Update;
+import org.skife.jdbi.v2.exceptions.CallbackFailedException;
+import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;
+import org.skife.jdbi.v2.tweak.HandleCallback;
+
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.function.Function;
+
+@ManageLifecycle
+public class SQLCatalogManager implements CatalogManager
+{
+  public static final String TABLES_TABLE = "tableDefs";
+
+  private static final String INSERT_TABLE =
+      "INSERT INTO %s\n" +
+      "  (schemaName, name, creationTime, updateTime, state, payload)\n" +
+      "  VALUES(:schemaName, :name, :creationTime, :updateTime, :state, 
:payload)";
+
+  private static final String UPDATE_HEAD =
+      "UPDATE %s\n SET\n";
+
+  private static final String WHERE_TABLE_ID =
+      "WHERE schemaName = :schemaName\n" +
+      "  AND name = :name\n";
+
+  private static final String SAFETY_CHECK =
+      "  AND updateTime = :oldVersion";
+
+  private static final String UPDATE_DEFN_UNSAFE =
+      UPDATE_HEAD +
+      "  payload = :payload,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String UPDATE_DEFN_SAFE =
+      UPDATE_DEFN_UNSAFE +
+      SAFETY_CHECK;
+
+  private static final String UPDATE_STATE =
+      UPDATE_HEAD +
+      "  state = :state,\n" +
+      "  updateTime = :updateTime\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_TABLE =
+      "SELECT creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_PAYLOAD =
+      "SELECT state, payload\n" +
+      "FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private static final String SELECT_ALL_TABLES =
+      "SELECT schemaName, name\n" +
+      "FROM %s\n" +
+      "ORDER BY schemaName, name";
+
+  private static final String SELECT_TABLES_IN_SCHEMA =
+      "SELECT name\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String SELECT_TABLE_DETAILS_IN_SCHEMA =
+      "SELECT name, creationTime, updateTime, state, payload\n" +
+      "FROM %s\n" +
+      "WHERE schemaName = :schemaName\n" +
+      "ORDER BY name";
+
+  private static final String DELETE_TABLE =
+      "DELETE FROM %s\n" +
+      WHERE_TABLE_ID;
+
+  private final MetastoreManager metastoreManager;
+  private final SQLMetadataConnector connector;
+  private final ObjectMapper jsonMapper;
+  private final IDBI dbi;
+  private final String tableName;
+  private final Deque<Listener> listeners = new ConcurrentLinkedDeque<>();
+
+  @Inject
+  public SQLCatalogManager(MetastoreManager metastoreManager)
+  {
+    if (!metastoreManager.isSql()) {
+      throw new ISE("SQLCatalogManager only works with SQL based metadata 
store at this time");
+    }
+    this.metastoreManager = metastoreManager;
+    this.connector = metastoreManager.sqlConnector();
+    this.dbi = connector.getDBI();
+    this.jsonMapper = metastoreManager.jsonMapper();
+    this.tableName = getTableDefnTable();
+  }
+
+  @Override
+  @LifecycleStart
+  public void start()
+  {
+    createTableDefnTable();
+  }
+
+  @Override
+  public void stop()
+  {
+  }
+
+  // Mimics what MetadataStorageTablesConfig should do.
+  public String getTableDefnTable()
+  {
+    final String base = metastoreManager.tablesConfig().getBase();
+    if (Strings.isNullOrEmpty(base)) {
+      return TABLES_TABLE;
+    } else {
+      return StringUtils.format("%s_%s", base, TABLES_TABLE);
+    }
+  }
+
+  // TODO: Move to SqlMetadataConnector
+  @Override
+  public void createTableDefnTable()
+  {
+    if (!metastoreManager.createTables()) {
+      return;
+    }
+    connector.createTable(
+        tableName,
+        ImmutableList.of(
+            StringUtils.format(
+                "CREATE TABLE %s (\n"

Review Comment:
   Out of the topic, I like [jOOQ](https://www.jooq.org/) much more than any 
other ways of writing SQL in java applications. jOOQ allows us to write SQL in 
java code. It's more convenient to understand, read and program.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to