Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Destination Redshift: Add generation_id and sync_id #40201

Merged
merged 1 commit into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ plugins {
}

airbyteJavaConnector {
cdkVersionRequired = '0.35.16'
cdkVersionRequired = '0.38.3'
features = ['db-destinations', 's3-destinations', 'typing-deduping']
useLocalCdk = false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ data:
connectorSubtype: database
connectorType: destination
definitionId: f7a7d195-377f-cf5b-70a5-be6b819019dc
dockerImageTag: 3.1.1
dockerImageTag: 3.2.0
dockerRepository: airbyte/destination-redshift
documentationUrl: https://docs.airbyte.com/integrations/destinations/redshift
githubIssueLabel: destination-redshift
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import io.airbyte.cdk.integrations.destination.async.model.PartialAirbyteRecordM
import io.airbyte.cdk.integrations.destination.async.state.FlushFailure
import io.airbyte.cdk.integrations.destination.jdbc.AbstractJdbcDestination.Companion.DISABLE_TYPE_DEDUPE
import io.airbyte.cdk.integrations.destination.jdbc.AbstractJdbcDestination.Companion.RAW_SCHEMA_OVERRIDE
import io.airbyte.cdk.integrations.destination.jdbc.typing_deduping.JdbcDestinationHandler
import io.airbyte.cdk.integrations.destination.s3.AesCbcEnvelopeEncryption
import io.airbyte.cdk.integrations.destination.s3.EncryptionConfig
import io.airbyte.cdk.integrations.destination.s3.EncryptionConfig.Companion.fromJson
Expand All @@ -61,6 +60,7 @@ import io.airbyte.integrations.destination.redshift.constants.RedshiftDestinatio
import io.airbyte.integrations.destination.redshift.operation.RedshiftStagingStorageOperation
import io.airbyte.integrations.destination.redshift.typing_deduping.RedshiftDV2Migration
import io.airbyte.integrations.destination.redshift.typing_deduping.RedshiftDestinationHandler
import io.airbyte.integrations.destination.redshift.typing_deduping.RedshiftGenerationIdMigration
import io.airbyte.integrations.destination.redshift.typing_deduping.RedshiftRawTableAirbyteMetaMigration
import io.airbyte.integrations.destination.redshift.typing_deduping.RedshiftSqlGenerator
import io.airbyte.integrations.destination.redshift.typing_deduping.RedshiftState
Expand All @@ -69,6 +69,7 @@ import io.airbyte.integrations.destination.redshift.util.RedshiftUtil
import io.airbyte.protocol.models.v0.AirbyteConnectionStatus
import io.airbyte.protocol.models.v0.AirbyteMessage
import io.airbyte.protocol.models.v0.AirbyteRecordMessageMeta
import io.airbyte.protocol.models.v0.AirbyteStreamStatusTraceMessage.AirbyteStreamStatus
import io.airbyte.protocol.models.v0.ConfiguredAirbyteCatalog
import io.airbyte.protocol.models.v0.ConnectorSpecification
import io.airbyte.protocol.models.v0.DestinationSyncMode
Expand All @@ -81,7 +82,6 @@ import java.util.concurrent.Executors
import java.util.function.Consumer
import javax.sql.DataSource
import org.apache.commons.lang3.NotImplementedException
import org.apache.commons.lang3.StringUtils
import org.jetbrains.annotations.VisibleForTesting
import org.slf4j.Logger
import org.slf4j.LoggerFactory
Expand Down Expand Up @@ -187,7 +187,11 @@ class RedshiftDestination : BaseConnector(), Destination {
isSchemaMismatch = true,
isFinalTableEmpty = true,
destinationState =
RedshiftState(needsSoftReset = false, isAirbyteMetaPresentInRaw = true),
RedshiftState(
needsSoftReset = false,
isAirbyteMetaPresentInRaw = true,
isGenerationIdPresent = true,
),
),
FileUploadFormat.CSV,
destinationColumns,
Expand All @@ -211,7 +215,7 @@ class RedshiftDestination : BaseConnector(), Destination {
)
streamOperation.finalizeTable(
streamConfig,
StreamSyncSummary(recordsWritten = Optional.of(1)),
StreamSyncSummary(recordsWritten = 1, AirbyteStreamStatus.COMPLETE),
)

// And now that we have a table, simulate the next sync startup.
Expand Down Expand Up @@ -315,14 +319,6 @@ class RedshiftDestination : BaseConnector(), Destination {
return RedshiftSqlGenerator(namingResolver, config)
}

private fun getDestinationHandler(
databaseName: String,
database: JdbcDatabase,
rawTableSchema: String
): JdbcDestinationHandler<RedshiftState> {
return RedshiftDestinationHandler(databaseName, database, rawTableSchema)
}

private fun getMigrations(
database: JdbcDatabase,
databaseName: String,
Expand All @@ -336,6 +332,7 @@ class RedshiftDestination : BaseConnector(), Destination {
sqlGenerator,
),
RedshiftRawTableAirbyteMetaMigration(database, databaseName),
RedshiftGenerationIdMigration(database, databaseName)
)
}

Expand Down Expand Up @@ -372,13 +369,7 @@ class RedshiftDestination : BaseConnector(), Destination {
else NoEncryption()
val s3Options = RedshiftUtil.findS3Options(config)
val s3Config: S3DestinationConfig = S3DestinationConfig.getS3DestinationConfig(s3Options)

val defaultNamespace = config["schema"].asText()
for (stream in catalog.streams) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this now happens in CatalogParser, so don't do it redundantly

if (StringUtils.isEmpty(stream.stream.namespace)) {
stream.stream.namespace = defaultNamespace
}
}

val sqlGenerator = RedshiftSqlGenerator(namingResolver, config)
val parsedCatalog: ParsedCatalog
Expand All @@ -388,10 +379,10 @@ class RedshiftDestination : BaseConnector(), Destination {
val rawNamespace: String
if (getRawNamespaceOverride(RAW_SCHEMA_OVERRIDE).isPresent) {
rawNamespace = getRawNamespaceOverride(RAW_SCHEMA_OVERRIDE).get()
catalogParser = CatalogParser(sqlGenerator, rawNamespace)
catalogParser = CatalogParser(sqlGenerator, defaultNamespace, rawNamespace)
} else {
rawNamespace = JavaBaseConstants.DEFAULT_AIRBYTE_INTERNAL_NAMESPACE
catalogParser = CatalogParser(sqlGenerator, rawNamespace)
catalogParser = CatalogParser(sqlGenerator, defaultNamespace, rawNamespace)
}
val redshiftDestinationHandler =
RedshiftDestinationHandler(databaseName, database, rawNamespace)
Expand Down Expand Up @@ -436,8 +427,7 @@ class RedshiftDestination : BaseConnector(), Destination {
},
onFlush = DefaultFlush(OPTIMAL_FLUSH_BATCH_SIZE, syncOperation),
catalog,
BufferManager(bufferMemoryLimit),
Optional.ofNullable(defaultNamespace),
BufferManager(defaultNamespace, bufferMemoryLimit),
FlushFailure(),
Executors.newFixedThreadPool(5),
AirbyteMessageDeserializer(getDataTransformer(parsedCatalog, defaultNamespace)),
Expand All @@ -463,7 +453,7 @@ class RedshiftDestination : BaseConnector(), Destination {
"com.amazon.redshift.ssl.NonValidatingFactory"
)

private val destinationColumns = JavaBaseConstants.DestinationColumns.V2_WITH_META
private val destinationColumns = JavaBaseConstants.DestinationColumns.V2_WITH_GENERATION

private const val OPTIMAL_FLUSH_BATCH_SIZE: Long = 50 * 1024 * 1024
private val bufferMemoryLimit: Long = (Runtime.getRuntime().maxMemory() * 0.5).toLong()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ class RedshiftStagingStorageOperation(
s3StorageOperations.createBucketIfNotExists()
}

override fun writeToStage(streamId: StreamId, data: SerializableBuffer) {
override fun writeToStage(streamConfig: StreamConfig, data: SerializableBuffer) {
val streamId = streamConfig.id
val objectPath: String = getStagingPath(streamId)
log.info {
"Uploading records to for ${streamId.rawNamespace}.${streamId.rawName} to path $objectPath"
Expand Down Expand Up @@ -201,7 +202,8 @@ class RedshiftStagingStorageOperation(
${JavaBaseConstants.COLUMN_NAME_AB_EXTRACTED_AT} TIMESTAMPTZ DEFAULT GETDATE(),
${JavaBaseConstants.COLUMN_NAME_AB_LOADED_AT} TIMESTAMPTZ,
${JavaBaseConstants.COLUMN_NAME_DATA} SUPER NOT NULL,
${JavaBaseConstants.COLUMN_NAME_AB_META} SUPER NULL
${JavaBaseConstants.COLUMN_NAME_AB_META} SUPER NULL,
${JavaBaseConstants.COLUMN_NAME_AB_GENERATION_ID} BIGINT NULL
)
""".trimIndent()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class RedshiftDV2Migration(
RedshiftState(
needsSoftReset = false,
isAirbyteMetaPresentInRaw = false,
isGenerationIdPresent = false
),
true,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,9 @@ class RedshiftDestinationHandler(
for (transaction in transactions) {
val transactionId = UUID.randomUUID()
if (logStatements) {
log.info(
"Executing sql {}-{}: {}",
queryId,
transactionId,
java.lang.String.join("\n", transaction)
)
log.info {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these log statements generated a compiler warning, so switch to the non-deprecated version

"Executing sql $queryId-$transactionId: ${transaction.joinToString("\n")}"
}
}
val startTime = System.currentTimeMillis()

Expand All @@ -113,7 +110,7 @@ class RedshiftDestinationHandler(
logStatements = logStatements
)
} catch (e: SQLException) {
log.error("Sql {}-{} failed", queryId, transactionId, e)
log.error(e) { "Sql $queryId-$transactionId failed" }
// This is a big hammer for something that should be much more targetted, only when
// executing the
// DROP TABLE command.
Expand All @@ -129,12 +126,9 @@ class RedshiftDestinationHandler(
throw e
}

log.info(
"Sql {}-{} completed in {} ms",
queryId,
transactionId,
System.currentTimeMillis() - startTime
)
log.info {
"Sql $queryId-$transactionId completed in ${System.currentTimeMillis() - startTime} ms"
}
}
}

Expand All @@ -156,7 +150,8 @@ class RedshiftDestinationHandler(
return RedshiftState(
json.hasNonNull("needsSoftReset") && json["needsSoftReset"].asBoolean(),
json.hasNonNull("isAirbyteMetaPresentInRaw") &&
json["isAirbyteMetaPresentInRaw"].asBoolean()
json["isAirbyteMetaPresentInRaw"].asBoolean(),
json.hasNonNull("isGenerationIdPresent") && json["isGenerationIdPresent"].asBoolean(),
)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Copyright (c) 2024 Airbyte, Inc., all rights reserved.
*/

package io.airbyte.integrations.destination.redshift.typing_deduping

import com.fasterxml.jackson.databind.JsonNode
import io.airbyte.cdk.db.jdbc.JdbcDatabase
import io.airbyte.cdk.integrations.base.JavaBaseConstants
import io.airbyte.integrations.base.destination.typing_deduping.DestinationHandler
import io.airbyte.integrations.base.destination.typing_deduping.DestinationInitialStatus
import io.airbyte.integrations.base.destination.typing_deduping.StreamConfig
import io.airbyte.integrations.base.destination.typing_deduping.migrators.Migration
import io.github.oshai.kotlinlogging.KotlinLogging

private val logger = KotlinLogging.logger {}

class RedshiftGenerationIdMigration(
private val database: JdbcDatabase,
private val databaseName: String,
) : Migration<RedshiftState> {
override fun migrateIfNecessary(
destinationHandler: DestinationHandler<RedshiftState>,
stream: StreamConfig,
state: DestinationInitialStatus<RedshiftState>
): Migration.MigrationResult<RedshiftState> {
if (state.destinationState.isGenerationIdPresent) {
logger.info {
"Skipping generation_id migration for ${stream.id.originalNamespace}.${stream.id.originalName} because our state says it's already done"
}
return Migration.MigrationResult(state.destinationState, invalidateInitialState = false)
}

if (!state.initialRawTableStatus.rawTableExists) {
// The raw table doesn't exist. No migration necessary. Update the state.
logger.info {
"Skipping generation_id migration for ${stream.id.originalNamespace}.${stream.id.originalName} because the raw table doesn't exist"
}
return Migration.MigrationResult(
state.destinationState.copy(isGenerationIdPresent = true),
invalidateInitialState = false
)
}

// Add generation_id to the raw table if necessary
val rawTableDefinitionQueryResult: List<JsonNode> =
database.queryJsons(
"""
SHOW COLUMNS
FROM TABLE "$databaseName"."${stream.id.rawNamespace}"."${stream.id.rawName}"
LIKE '${JavaBaseConstants.COLUMN_NAME_AB_GENERATION_ID}'
""".trimIndent()
)
if (rawTableDefinitionQueryResult.isNotEmpty()) {
logger.info {
"${stream.id.originalNamespace}.${stream.id.originalName}: Skipping generation_id migration for raw table because it already has the generation_id column"
}
} else {
logger.info {
"Migrating generation_id for table ${stream.id.rawNamespace}.${stream.id.rawName}"
}
// Quote for raw table columns
val alterRawTableSql =
"""
ALTER TABLE "${stream.id.rawNamespace}"."${stream.id.rawName}"
ADD COLUMN "${JavaBaseConstants.COLUMN_NAME_AB_GENERATION_ID}" BIGINT;
""".trimIndent()
database.execute(alterRawTableSql)
}

// Add generation_id to the final table if necessary
// As a slight optimization, only do this if we previously detected that the final table
// schema is wrong
if (state.isFinalTablePresent && state.isSchemaMismatch) {
val finalTableColumnQueryResult: List<JsonNode> =
database.queryJsons(
"""
SHOW COLUMNS
FROM TABLE "$databaseName"."${stream.id.finalNamespace}"."${stream.id.finalName}"
LIKE '${JavaBaseConstants.COLUMN_NAME_AB_GENERATION_ID}'
""".trimIndent()
)
if (finalTableColumnQueryResult.isNotEmpty()) {
logger.info {
"${stream.id.originalNamespace}.${stream.id.originalName}: Skipping generation_id migration for final table because it already has the generation_id column"
}
} else {
logger.info {
"Migrating generation_id for table ${stream.id.finalNamespace}.${stream.id.finalName}"
}
database.execute(
"""
ALTER TABLE "${stream.id.finalNamespace}"."${stream.id.finalName}"
ADD COLUMN "${JavaBaseConstants.COLUMN_NAME_AB_GENERATION_ID}" BIGINT NULL;
""".trimIndent()
)
}
} else {
logger.info {
"${stream.id.originalNamespace}.${stream.id.originalName}: Skipping generation_id migration for final table. Final table exists: ${state.isFinalTablePresent}; final table schema is incorrect: ${state.isSchemaMismatch}"
}
}

return Migration.MigrationResult(
state.destinationState.copy(isGenerationIdPresent = true),
invalidateInitialState = true
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import io.airbyte.integrations.base.destination.typing_deduping.UnsupportedOneOf
import io.airbyte.integrations.destination.redshift.constants.RedshiftDestinationConstants
import io.airbyte.protocol.models.AirbyteRecordMessageMetaChange
import java.sql.Timestamp
import java.util.*
import java.util.Optional
import java.util.stream.Collectors
import org.jooq.Condition
import org.jooq.DataType
Expand Down Expand Up @@ -146,7 +146,7 @@ open class RedshiftSqlGenerator(
* @param arrays
* @return
*/
fun arrayConcatStmt(arrays: List<Field<*>?>): Field<*>? {
private fun arrayConcatStmt(arrays: List<Field<*>?>): Field<*>? {
if (arrays.isEmpty()) {
return DSL.field("ARRAY()") // Return an empty string if the list is empty
}
Expand All @@ -165,7 +165,7 @@ open class RedshiftSqlGenerator(
return result
}

fun toCastingErrorCaseStmt(column: ColumnId, type: AirbyteType): Field<*> {
private fun toCastingErrorCaseStmt(column: ColumnId, type: AirbyteType): Field<*> {
val field: Field<*> =
DSL.field(DSL.quotedName(JavaBaseConstants.COLUMN_NAME_DATA, column.originalName))
// Just checks if data is not null but casted data is null. This also accounts for
Expand Down Expand Up @@ -260,7 +260,14 @@ open class RedshiftSqlGenerator(
"OBJECT",
superType,
DSL.`val`(AIRBYTE_META_COLUMN_CHANGES_KEY),
airbyteMetaChangesArray
airbyteMetaChangesArray,
DSL.`val`(JavaBaseConstants.AIRBYTE_META_SYNC_ID_KEY),
DSL.field(
DSL.quotedName(
JavaBaseConstants.COLUMN_NAME_AB_META,
JavaBaseConstants.AIRBYTE_META_SYNC_ID_KEY
)
),
)
.`as`(JavaBaseConstants.COLUMN_NAME_AB_META)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ package io.airbyte.integrations.destination.redshift.typing_deduping

import io.airbyte.integrations.base.destination.typing_deduping.migrators.MinimumDestinationState

data class RedshiftState(val needsSoftReset: Boolean, val isAirbyteMetaPresentInRaw: Boolean) :
MinimumDestinationState {
data class RedshiftState(
val needsSoftReset: Boolean,
val isAirbyteMetaPresentInRaw: Boolean,
val isGenerationIdPresent: Boolean,
) : MinimumDestinationState {
override fun needsSoftReset(): Boolean {
return needsSoftReset
}
Expand Down
Loading
Loading