Skip to content

Instantly share code, notes, and snippets.

@giovannicandido
Created October 28, 2023 15:32
Show Gist options
  • Save giovannicandido/570717e6eb529b08443cbf50df9bfd2b to your computer and use it in GitHub Desktop.
Save giovannicandido/570717e6eb529b08443cbf50df9bfd2b to your computer and use it in GitHub Desktop.
Resets sequences between junit integration tests
package com.kugelbit.mercado.estoque.test
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationContext
import org.springframework.core.env.Environment
import java.sql.SQLException
import javax.sql.DataSource
object DbTestUtil {
private val log = LoggerFactory.getLogger(DbTestUtil::class.java)
private val allowedSequenceNames = setOf(
"brand_seq",
"product_seq",
"product_category_seq",
"market_seq",
"main_stock_seq"
)
@Throws(SQLException::class, SQLException::class)
fun resetAutoIncrementColumns(
applicationContext: ApplicationContext,
vararg sequenceNames: String
) {
log.info("Initiating reset of sequences")
val dataSource = applicationContext.getBean(DataSource::class.java)
val resetSqlTemplate = "ALTER SEQUENCE %s RESTART WITH 1"
dataSource.connection.use { dbConnection ->
//Create SQL statements that reset the auto increment columns and invoke
//the created SQL statements.
for (sequence in sequenceNames) {
if (!allowedSequenceNames.contains(sequence)) {
throw RuntimeException("sequence name is not in allowed list, please add it for security reasons")
}
log.info("Reseting sequence: $sequence")
val resetSql = String.format(resetSqlTemplate, sequence)
log.info("Reseting sequence sql: $resetSql")
dbConnection.prepareStatement(resetSql).use { statement -> statement.execute() }
}
}
}
private fun getResetSqlTemplate(applicationContext: ApplicationContext): String {
//Read the SQL template from the properties file
val environment = applicationContext.getBean(
Environment::class.java
)
return environment.getRequiredProperty("test.reset.sql.template")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment