zachjsh commented on code in PR #13165: URL: https://github.com/apache/druid/pull/13165#discussion_r1012528048
########## extensions-core/druid-catalog/src/main/java/org/apache/druid/catalog/storage/sql/SQLCatalogManager.java: ########## @@ -0,0 +1,777 @@ +/* + * 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.core.type.TypeReference; +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.CatalogException; +import org.apache.druid.catalog.CatalogException.DuplicateKeyException; +import org.apache.druid.catalog.CatalogException.NotFoundException; +import org.apache.druid.catalog.model.ColumnSpec; +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.MetadataStorageManager; +import org.apache.druid.catalog.sync.CatalogUpdateListener; +import org.apache.druid.catalog.sync.UpdateEvent; +import org.apache.druid.catalog.sync.UpdateEvent.EventType; +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.jackson.JacksonUtils; +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.io.IOException; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentLinkedDeque; + +@ManageLifecycle +public class SQLCatalogManager implements CatalogManager +{ + public static final String TABLES_TABLE = "tableDefs"; + + private final MetadataStorageManager metastoreManager; + private final SQLMetadataConnector connector; + private final ObjectMapper jsonMapper; + private final IDBI dbi; + private final String tableName; + private final Deque<CatalogUpdateListener> listeners = new ConcurrentLinkedDeque<>(); + + @Inject + public SQLCatalogManager(MetadataStorageManager 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(); + } + + public static final String CREATE_TABLE = + "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" + + " tableType VARCHAR(20) NOT NULL,\n" + + " properties %s,\n" + + " columns %s,\n" + + " PRIMARY KEY(schemaName, name)\n" + + ")"; + + // TODO: Move to SqlMetadataConnector + public void createTableDefnTable() + { + if (!metastoreManager.config().isCreateTables()) { + return; + } + connector.createTable( + tableName, + ImmutableList.of( + StringUtils.format( + CREATE_TABLE, + tableName, + connector.getPayloadType(), + connector.getPayloadType() + ) + ) + ); + } + + private static final String INSERT_TABLE = + "INSERT INTO %s\n" + + " (schemaName, name, creationTime, updateTime, state,\n" + + " tableType, properties, columns)\n" + + " VALUES(:schemaName, :name, :creationTime, :updateTime, :state,\n" + + " :tableType, :properties, :columns)"; + + @Override + public long create(TableMetadata table) throws DuplicateKeyException + { + try { + return dbi.withHandle( + new HandleCallback<Long>() + { + @Override + public Long withHandle(Handle handle) throws DuplicateKeyException + { + final TableSpec spec = table.spec(); + final long updateTime = System.currentTimeMillis(); + final Update stmt = handle + .createStatement(statement(INSERT_TABLE)) + .bind("schemaName", table.id().schema()) + .bind("name", table.id().name()) + .bind("creationTime", updateTime) + .bind("updateTime", updateTime) + .bind("state", TableMetadata.TableState.ACTIVE.code()) + .bind("tableType", spec.type()) + .bind("properties", JacksonUtils.toBytes(jsonMapper, spec.properties())) + .bind("columns", JacksonUtils.toBytes(jsonMapper, spec.columns())); + try { + stmt.execute(); + } + catch (UnableToExecuteStatementException e) { + if (DbUtils.isDuplicateRecordException(e)) { + throw new DuplicateKeyException( + "Tried to insert a duplicate table: %s", + table.sqlName() + ); + } else { + throw e; + } + } + sendAddition(table, updateTime); + return updateTime; + } + } + ); + } + catch (CallbackFailedException e) { + if (e.getCause() instanceof DuplicateKeyException) { + throw (DuplicateKeyException) e.getCause(); + } + throw e; + } + } + + private static final String SELECT_TABLE = + "SELECT creationTime, updateTime, state, tableType, properties, columns\n" + + "FROM %s\n" + + "WHERE schemaName = :schemaName\n" + + " AND name = :name\n"; + + @Override + public TableMetadata read(TableId id) throws NotFoundException + { + try { + return dbi.withHandle( + new HandleCallback<TableMetadata>() + { + @Override + public TableMetadata withHandle(Handle handle) throws NotFoundException + { + final Query<Map<String, Object>> query = handle + .createQuery(statement(SELECT_TABLE)) + .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)), + tableSpecFromBytes(jsonMapper, r.getString(4), r.getBytes(5), r.getBytes(6)) + )) + .iterator(); + if (resultIterator.hasNext()) { + return resultIterator.next(); + } + throw tableNotFound(id); + } + } + ); + } + catch (CallbackFailedException e) { + if (e.getCause() instanceof NotFoundException) { + throw (NotFoundException) e.getCause(); + } + throw e; + } + } + + private static final String REPLACE_SPEC_STMT = + "UPDATE %s\n SET\n" + + " tableType = :tableType,\n" + Review Comment: should a table be able to change types? -- 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]
