|
| 1 | +/* |
| 2 | + * Copyright (c) 2023 Airbyte, Inc., all rights reserved. |
| 3 | + */ |
| 4 | + |
| 5 | +package io.airbyte.integrations.destination.snowflake.typing_deduping; |
| 6 | + |
| 7 | +import static io.airbyte.integrations.base.JavaBaseConstants.DEFAULT_AIRBYTE_INTERNAL_NAMESPACE; |
| 8 | +import static io.airbyte.integrations.destination.snowflake.SnowflakeInternalStagingDestination.RAW_SCHEMA_OVERRIDE; |
| 9 | + |
| 10 | +import io.airbyte.db.jdbc.JdbcDatabase; |
| 11 | +import io.airbyte.integrations.base.TypingAndDedupingFlag; |
| 12 | +import io.airbyte.integrations.base.destination.typing_deduping.StreamConfig; |
| 13 | +import io.airbyte.integrations.base.destination.typing_deduping.StreamId; |
| 14 | +import io.airbyte.integrations.base.destination.typing_deduping.V2TableMigrator; |
| 15 | +import io.airbyte.protocol.models.v0.DestinationSyncMode; |
| 16 | +import java.sql.SQLException; |
| 17 | +import java.util.LinkedHashMap; |
| 18 | +import java.util.Optional; |
| 19 | +import org.slf4j.Logger; |
| 20 | +import org.slf4j.LoggerFactory; |
| 21 | + |
| 22 | +public class SnowflakeV2TableMigrator implements V2TableMigrator<SnowflakeTableDefinition> { |
| 23 | + |
| 24 | + private static final Logger LOGGER = LoggerFactory.getLogger(SnowflakeV2TableMigrator.class); |
| 25 | + |
| 26 | + private final JdbcDatabase database; |
| 27 | + private final String rawNamespace; |
| 28 | + private final String databaseName; |
| 29 | + private final SnowflakeSqlGenerator generator; |
| 30 | + private final SnowflakeDestinationHandler handler; |
| 31 | + |
| 32 | + public SnowflakeV2TableMigrator(final JdbcDatabase database, |
| 33 | + final String databaseName, |
| 34 | + final SnowflakeSqlGenerator generator, |
| 35 | + final SnowflakeDestinationHandler handler) { |
| 36 | + this.database = database; |
| 37 | + this.databaseName = databaseName; |
| 38 | + this.generator = generator; |
| 39 | + this.handler = handler; |
| 40 | + this.rawNamespace = TypingAndDedupingFlag.getRawNamespaceOverride(RAW_SCHEMA_OVERRIDE).orElse(DEFAULT_AIRBYTE_INTERNAL_NAMESPACE); |
| 41 | + } |
| 42 | + |
| 43 | + @Override |
| 44 | + public void migrateIfNecessary(final StreamConfig streamConfig) throws Exception { |
| 45 | + final StreamId caseSensitiveStreamId = buildStreamId_caseSensitive( |
| 46 | + streamConfig.id().originalNamespace(), |
| 47 | + streamConfig.id().originalName(), |
| 48 | + rawNamespace); |
| 49 | + final boolean syncModeRequiresMigration = streamConfig.destinationSyncMode() != DestinationSyncMode.OVERWRITE; |
| 50 | + final boolean existingTableCaseSensitiveExists = findExistingTable_caseSensitive(caseSensitiveStreamId).isPresent(); |
| 51 | + final boolean existingTableUppercaseDoesNotExist = !handler.findExistingTable(streamConfig.id()).isPresent(); |
| 52 | + LOGGER.info( |
| 53 | + "Checking whether upcasing migration is necessary for {}.{}. Sync mode requires migration: {}; existing case-sensitive table exists: {}; existing uppercased table does not exist: {}", |
| 54 | + streamConfig.id().originalNamespace(), |
| 55 | + streamConfig.id().originalName(), |
| 56 | + syncModeRequiresMigration, |
| 57 | + existingTableCaseSensitiveExists, |
| 58 | + existingTableUppercaseDoesNotExist); |
| 59 | + if (syncModeRequiresMigration && existingTableCaseSensitiveExists && existingTableUppercaseDoesNotExist) { |
| 60 | + LOGGER.info( |
| 61 | + "Executing upcasing migration for {}.{}", |
| 62 | + streamConfig.id().originalNamespace(), |
| 63 | + streamConfig.id().originalName()); |
| 64 | + handler.execute(generator.softReset(streamConfig)); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + // These methods were copied from |
| 69 | + // https://github.com/airbytehq/airbyte/blob/d5fdb1b982d464f54941bf9a830b9684fb47d249/airbyte-integrations/connectors/destination-snowflake/src/main/java/io/airbyte/integrations/destination/snowflake/typing_deduping/SnowflakeSqlGenerator.java |
| 70 | + // which is the highest version of destination-snowflake that still uses quoted+case-sensitive |
| 71 | + // identifiers |
| 72 | + private static StreamId buildStreamId_caseSensitive(final String namespace, final String name, final String rawNamespaceOverride) { |
| 73 | + // No escaping needed, as far as I can tell. We quote all our identifier names. |
| 74 | + return new StreamId( |
| 75 | + escapeIdentifier_caseSensitive(namespace), |
| 76 | + escapeIdentifier_caseSensitive(name), |
| 77 | + escapeIdentifier_caseSensitive(rawNamespaceOverride), |
| 78 | + escapeIdentifier_caseSensitive(StreamId.concatenateRawTableName(namespace, name)), |
| 79 | + namespace, |
| 80 | + name); |
| 81 | + } |
| 82 | + |
| 83 | + private static String escapeIdentifier_caseSensitive(final String identifier) { |
| 84 | + // Note that we don't need to escape backslashes here! |
| 85 | + // The only special character in an identifier is the double-quote, which needs to be doubled. |
| 86 | + return identifier.replace("\"", "\"\""); |
| 87 | + } |
| 88 | + |
| 89 | + // And this was taken from |
| 90 | + // https://github.com/airbytehq/airbyte/blob/master/airbyte-integrations/connectors/destination-snowflake/src/main/java/io/airbyte/integrations/destination/snowflake/typing_deduping/SnowflakeDestinationHandler.java |
| 91 | + public Optional<SnowflakeTableDefinition> findExistingTable_caseSensitive(final StreamId id) throws SQLException { |
| 92 | + // The obvious database.getMetaData().getColumns() solution doesn't work, because JDBC translates |
| 93 | + // VARIANT as VARCHAR |
| 94 | + final LinkedHashMap<String, String> columns = database.queryJsons( |
| 95 | + """ |
| 96 | + SELECT column_name, data_type |
| 97 | + FROM information_schema.columns |
| 98 | + WHERE table_catalog = ? |
| 99 | + AND table_schema = ? |
| 100 | + AND table_name = ? |
| 101 | + ORDER BY ordinal_position; |
| 102 | + """, |
| 103 | + databaseName.toUpperCase(), |
| 104 | + id.finalNamespace(), |
| 105 | + id.finalName()).stream() |
| 106 | + .collect(LinkedHashMap::new, |
| 107 | + (map, row) -> map.put(row.get("COLUMN_NAME").asText(), row.get("DATA_TYPE").asText()), |
| 108 | + LinkedHashMap::putAll); |
| 109 | + // TODO query for indexes/partitioning/etc |
| 110 | + |
| 111 | + if (columns.isEmpty()) { |
| 112 | + return Optional.empty(); |
| 113 | + } else { |
| 114 | + return Optional.of(new SnowflakeTableDefinition(columns)); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | +} |
0 commit comments