[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75EWZXZVF8WS3PR0SPRXZVN":3,"skill-same:01M75EWZXZVF8WS3PR0SPRXZVN":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":6,"updatedAt":32,"install":33,"resources":46},"01M75EWZXZVF8WS3PR0SPRXZVN","kotlin-exposed-patterns",null,"JetBrains Exposed ORM patterns including DSL queries, DAO pattern, transactions, HikariCP connection pooling, Flyway migrations, and repository pattern.","agisota\u002Fold-one","agisota","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F121413592?v=4","01M75B4BRNT67EC1NDRT8QZEP2","01M75B4BS7QR9VP580MSCPTS3X",3,"MIT","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fkotlin-exposed-patterns\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: kotlin-exposed-patterns\ndescription: JetBrains Exposed ORM patterns including DSL queries, DAO pattern, transactions, HikariCP connection pooling, Flyway migrations, and repository pattern.\norigin: ECC\n---\n\n# Kotlin Exposed Patterns\n\nComprehensive patterns for database access with JetBrains Exposed ORM, including DSL queries, DAO, transactions, and production-ready configuration.\n\n## When to Use\n\n- Setting up database access with Exposed\n- Writing SQL queries using Exposed DSL or DAO\n- Configuring connection pooling with HikariCP\n- Creating database migrations with Flyway\n- Implementing the repository pattern with Exposed\n- Handling JSON columns and complex queries\n\n## How It Works\n\nExposed provides two query styles: DSL for direct SQL-like expressions and DAO for entity lifecycle management. HikariCP manages a pool of reusable database connections configured via `HikariConfig`. Flyway runs versioned SQL migration scripts at startup to keep the schema in sync. All database operations run inside `newSuspendedTransaction` blocks for coroutine safety and atomicity. The repository pattern wraps Exposed queries behind an interface so business logic stays decoupled from the data layer and tests can use an in-memory H2 database.\n\n## Examples\n\n### DSL Query\n\n```kotlin\nsuspend fun findUserById(id: UUID): UserRow? =\n    newSuspendedTransaction {\n        UsersTable.selectAll()\n            .where { UsersTable.id eq id }\n            .map { it.toUser() }\n            .singleOrNull()\n    }\n```\n\n### DAO Entity Usage\n\n```kotlin\nsuspend fun createUser(request: CreateUserRequest): User =\n    newSuspendedTransaction {\n        UserEntity.new {\n            name = request.name\n            email = request.email\n            role = request.role\n        }.toModel()\n    }\n```\n\n### HikariCP Configuration\n\n```kotlin\nval hikariConfig = HikariConfig().apply {\n    driverClassName = config.driver\n    jdbcUrl = config.url\n    username = config.username\n    password = config.password\n    maximumPoolSize = config.maxPoolSize\n    isAutoCommit = false\n    transactionIsolation = \"TRANSACTION_READ_COMMITTED\"\n    validate()\n}\n```\n\n## Database Setup\n\n### HikariCP Connection Pooling\n\n```kotlin\n\u002F\u002F DatabaseFactory.kt\nobject DatabaseFactory {\n    fun create(config: DatabaseConfig): Database {\n        val hikariConfig = HikariConfig().apply {\n            driverClassName = config.driver\n            jdbcUrl = config.url\n            username = config.username\n            password = config.password\n            maximumPoolSize = config.maxPoolSize\n            isAutoCommit = false\n            transactionIsolation = \"TRANSACTION_READ_COMMITTED\"\n            validate()\n        }\n\n        return Database.connect(HikariDataSource(hikariConfig))\n    }\n}\n\ndata class DatabaseConfig(\n    val url: String,\n    val driver: String = \"org.postgresql.Driver\",\n    val username: String = \"\",\n    val password: String = \"\",\n    val maxPoolSize: Int = 10,\n)\n```\n\n### Flyway Migrations\n\n```kotlin\n\u002F\u002F FlywayMigration.kt\nfun runMigrations(config: DatabaseConfig) {\n    Flyway.configure()\n        .dataSource(config.url, config.username, config.password)\n        .locations(\"classpath:db\u002Fmigration\")\n        .baselineOnMigrate(true)\n        .load()\n        .migrate()\n}\n\n\u002F\u002F Application startup\nfun Application.module() {\n    val config = DatabaseConfig(\n        url = environment.config.property(\"database.url\").getString(),\n        username = environment.config.property(\"database.username\").getString(),\n        password = environment.config.property(\"database.password\").getString(),\n    )\n    runMigrations(config)\n    val database = DatabaseFactory.create(config)\n    \u002F\u002F ...\n}\n```\n\n### Migration Files\n\n```sql\n-- src\u002Fmain\u002Fresources\u002Fdb\u002Fmigration\u002FV1__create_users.sql\nCREATE TABLE users (\n    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n    name VARCHAR(100) NOT NULL,\n    email VARCHAR(255) NOT NULL UNIQUE,\n    role VARCHAR(20) NOT NULL DEFAULT 'USER',\n    metadata JSONB,\n    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n);\n\nCREATE INDEX idx_users_email ON users(email);\nCREATE INDEX idx_users_role ON users(role);\n```\n\n## Table Definitions\n\n### DSL Style Tables\n\n```kotlin\n\u002F\u002F tables\u002FUsersTable.kt\nobject UsersTable : UUIDTable(\"users\") {\n    val name = varchar(\"name\", 100)\n    val email = varchar(\"email\", 255).uniqueIndex()\n    val role = enumerationByName\u003CRole>(\"role\", 20)\n    val metadata = jsonb\u003CUserMetadata>(\"metadata\", Json.Default).nullable()\n    val createdAt = timestampWithTimeZone(\"created_at\").defaultExpression(CurrentTimestampWithTimeZone)\n    val updatedAt = timestampWithTimeZone(\"updated_at\").defaultExpression(CurrentTimestampWithTimeZone)\n}\n\nobject OrdersTable : UUIDTable(\"orders\") {\n    val userId = uuid(\"user_id\").references(UsersTable.id)\n    val status = enumerationByName\u003COrderStatus>(\"status\", 20)\n    val totalAmount = long(\"total_amount\")\n    val currency = varchar(\"currency\", 3)\n    val createdAt = timestampWithTimeZone(\"created_at\").defaultExpression(CurrentTimestampWithTimeZone)\n}\n\nobject OrderItemsTable : UUIDTable(\"order_items\") {\n    val orderId = uuid(\"order_id\").references(OrdersTable.id, onDelete = ReferenceOption.CASCADE)\n    val productId = uuid(\"product_id\")\n    val quantity = integer(\"quantity\")\n    val unitPrice = long(\"unit_price\")\n}\n```\n\n### Composite Tables\n\n```kotlin\nobject UserRolesTable : Table(\"user_roles\") {\n    val userId = uuid(\"user_id\").references(UsersTable.id, onDelete = ReferenceOption.CASCADE)\n    val roleId = uuid(\"role_id\").references(RolesTable.id, onDelete = ReferenceOption.CASCADE)\n    override val primaryKey = PrimaryKey(userId, roleId)\n}\n```\n\n## DSL Queries\n\n### Basic CRUD\n\n```kotlin\n\u002F\u002F Insert\nsuspend fun insertUser(name: String, email: String, role: Role): UUID =\n    newSuspendedTransaction {\n        UsersTable.insertAndGetId {\n            it[UsersTable.name] = name\n            it[UsersTable.email] = email\n            it[UsersTable.role] = role\n        }.value\n    }\n\n\u002F\u002F Select by ID\nsuspend fun findUserById(id: UUID): UserRow? =\n    newSuspendedTransaction {\n        UsersTable.selectAll()\n            .where { UsersTable.id eq id }\n            .map { it.toUser() }\n            .singleOrNull()\n    }\n\n\u002F\u002F Select with conditions\nsuspend fun findActiveAdmins(): List\u003CUserRow> =\n    newSuspendedTransaction {\n        UsersTable.selectAll()\n            .where { (UsersTable.role eq Role.ADMIN) }\n            .orderBy(UsersTable.name)\n            .map { it.toUser() }\n    }\n\n\u002F\u002F Update\nsuspend fun updateUserEmail(id: UUID, newEmail: String): Boolean =\n    newSuspendedTransaction {\n        UsersTable.update({ UsersTable.id eq id }) {\n            it[email] = newEmail\n            it[updatedAt] = CurrentTimestampWithTimeZone\n        } > 0\n    }\n\n\u002F\u002F Delete\nsuspend fun deleteUser(id: UUID): Boolean =\n    newSuspendedTransaction {\n        UsersTable.deleteWhere { UsersTable.id eq id } > 0\n    }\n\n\u002F\u002F Row mapping\nprivate fun ResultRow.toUser() = UserRow(\n    id = this[UsersTable.id].value,\n    name = this[UsersTable.name],\n    email = this[UsersTable.email],\n    role = this[UsersTable.role],\n    metadata = this[UsersTable.metadata],\n    createdAt = this[UsersTable.createdAt],\n    updatedAt = this[UsersTable.updatedAt],\n)\n```\n\n### Advanced Queries\n\n```kotlin\n\u002F\u002F Join queries\nsuspend fun findOrdersWithUser(userId: UUID): List\u003COrderWithUser> =\n    newSuspendedTransaction {\n        (OrdersTable innerJoin UsersTable)\n            .selectAll()\n            .where { OrdersTable.userId eq userId }\n            .orderBy(OrdersTable.createdAt, SortOrder.DESC)\n            .map { row ->\n                OrderWithUser(\n                    orderId = row[OrdersTable.id].value,\n                    status = row[OrdersTable.status],\n                    totalAmount = row[OrdersTable.totalAmount],\n                    userName = row[UsersTable.name],\n                )\n            }\n    }\n\n\u002F\u002F Aggregation\nsuspend fun countUsersByRole(): Map\u003CRole, Long> =\n    newSuspendedTransaction {\n        UsersTable\n            .select(UsersTable.role, UsersTable.id.count())\n            .groupBy(UsersTable.role)\n            .associate { row ->\n                row[UsersTable.role] to row[UsersTable.id.count()]\n            }\n    }\n\n\u002F\u002F Subqueries\nsuspend fun findUsersWithOrders(): List\u003CUserRow> =\n    newSuspendedTransaction {\n        UsersTable.selectAll()\n            .where {\n                UsersTable.id inSubQuery\n                    OrdersTable.select(OrdersTable.userId).withDistinct()\n            }\n            .map { it.toUser() }\n    }\n\n\u002F\u002F LIKE and pattern matching — always escape user input to prevent wildcard injection\nprivate fun escapeLikePattern(input: String): String =\n    input.replace(\"\\\\\", \"\\\\\\\\\").replace(\"%\", \"\\\\%\").replace(\"_\", \"\\\\_\")\n\nsuspend fun searchUsers(query: String): List\u003CUserRow> =\n    newSuspendedTransaction {\n        val sanitized = escapeLikePattern(query.lowercase())\n        UsersTable.selectAll()\n            .where {\n                (UsersTable.name.lowerCase() like \"%${sanitized}%\") or\n                    (UsersTable.email.lowerCase() like \"%${sanitized}%\")\n            }\n            .map { it.toUser() }\n    }\n```\n\n### Pagination\n\n```kotlin\ndata class Page\u003CT>(\n    val data: List\u003CT>,\n    val total: Long,\n    val page: Int,\n    val limit: Int,\n) {\n    val totalPages: Int get() = ((total + limit - 1) \u002F limit).toInt()\n    val hasNext: Boolean get() = page \u003C totalPages\n    val hasPrevious: Boolean get() = page > 1\n}\n\nsuspend fun findUsersPaginated(page: Int, limit: Int): Page\u003CUserRow> =\n    newSuspendedTransaction {\n        val total = UsersTable.selectAll().count()\n        val data = UsersTable.selectAll()\n            .orderBy(UsersTable.createdAt, SortOrder.DESC)\n            .limit(limit)\n            .offset(((page - 1) * limit).toLong())\n            .map { it.toUser() }\n\n        Page(data = data, total = total, page = page, limit = limit)\n    }\n```\n\n### Batch Operations\n\n```kotlin\n\u002F\u002F Batch insert\nsuspend fun insertUsers(users: List\u003CCreateUserRequest>): List\u003CUUID> =\n    newSuspendedTransaction {\n        UsersTable.batchInsert(users) { user ->\n            this[UsersTable.name] = user.name\n            this[UsersTable.email] = user.email\n            this[UsersTable.role] = user.role\n        }.map { it[UsersTable.id].value }\n    }\n\n\u002F\u002F Upsert (insert or update on conflict)\nsuspend fun upsertUser(id: UUID, name: String, email: String) {\n    newSuspendedTransaction {\n        UsersTable.upsert(UsersTable.email) {\n            it[UsersTable.id] = EntityID(id, UsersTable)\n            it[UsersTable.name] = name\n            it[UsersTable.email] = email\n            it[updatedAt] = CurrentTimestampWithTimeZone\n        }\n    }\n}\n```\n\n## DAO Pattern\n\n### Entity Definitions\n\n```kotlin\n\u002F\u002F entities\u002FUserEntity.kt\nclass UserEntity(id: EntityID\u003CUUID>) : UUIDEntity(id) {\n    companion object : UUIDEntityClass\u003CUserEntity>(UsersTable)\n\n    var name by UsersTable.name\n    var email by UsersTable.email\n    var role by UsersTable.role\n    var metadata by UsersTable.metadata\n    var createdAt by UsersTable.createdAt\n    var updatedAt by UsersTable.updatedAt\n\n    val orders by OrderEntity referrersOn OrdersTable.userId\n\n    fun toModel(): User = User(\n        id = id.value,\n        name = name,\n        email = email,\n        role = role,\n        metadata = metadata,\n        createdAt = createdAt,\n        updatedAt = updatedAt,\n    )\n}\n\nclass OrderEntity(id: EntityID\u003CUUID>) : UUIDEntity(id) {\n    companion object : UUIDEntityClass\u003COrderEntity>(OrdersTable)\n\n    var user by UserEntity referencedOn OrdersTable.userId\n    var status by OrdersTable.status\n    var totalAmount by OrdersTable.totalAmount\n    var currency by OrdersTable.currency\n    var createdAt by OrdersTable.createdAt\n\n    val items by OrderItemEntity referrersOn OrderItemsTable.orderId\n}\n```\n\n### DAO Operations\n\n```kotlin\nsuspend fun findUserByEmail(email: String): User? =\n    newSuspendedTransaction {\n        UserEntity.find { UsersTable.email eq email }\n            .firstOrNull()\n            ?.toModel()\n    }\n\nsuspend fun createUser(request: CreateUserRequest): User =\n    newSuspendedTransaction {\n        UserEntity.new {\n            name = request.name\n            email = request.email\n            role = request.role\n        }.toModel()\n    }\n\nsuspend fun updateUser(id: UUID, request: UpdateUserRequest): User? =\n    newSuspendedTransaction {\n        UserEntity.findById(id)?.apply {\n            request.name?.let { name = it }\n            request.email?.let { email = it }\n            updatedAt = OffsetDateTime.now(ZoneOffset.UTC)\n        }?.toModel()\n    }\n```\n\n## Transactions\n\n### Suspend Transaction Support\n\n```kotlin\n\u002F\u002F Good: Use newSuspendedTransaction for coroutine support\nsuspend fun performDatabaseOperation(): Result\u003CUser> =\n    runCatching {\n        newSuspendedTransaction {\n            val user = UserEntity.new {\n                name = \"Alice\"\n                email = \"alice@example.com\"\n            }\n            \u002F\u002F All operations in this block are atomic\n            user.toModel()\n        }\n    }\n\n\u002F\u002F Good: Nested transactions with savepoints\nsuspend fun transferFunds(fromId: UUID, toId: UUID, amount: Long) {\n    newSuspendedTransaction {\n        val from = UserEntity.findById(fromId) ?: throw NotFoundException(\"User $fromId not found\")\n        val to = UserEntity.findById(toId) ?: throw NotFoundException(\"User $toId not found\")\n\n        \u002F\u002F Debit\n        from.balance -= amount\n        \u002F\u002F Credit\n        to.balance += amount\n\n        \u002F\u002F Both succeed or both fail\n    }\n}\n```\n\n### Transaction Isolation\n\n```kotlin\nsuspend fun readCommittedQuery(): List\u003CUser> =\n    newSuspendedTransaction(transactionIsolation = Connection.TRANSACTION_READ_COMMITTED) {\n        UserEntity.all().map { it.toModel() }\n    }\n\nsuspend fun serializableOperation() {\n    newSuspendedTransaction(transactionIsolation = Connection.TRANSACTION_SERIALIZABLE) {\n        \u002F\u002F Strictest isolation level for critical operations\n    }\n}\n```\n\n## Repository Pattern\n\n### Interface Definition\n\n```kotlin\ninterface UserRepository {\n    suspend fun findById(id: UUID): User?\n    suspend fun findByEmail(email: String): User?\n    suspend fun findAll(page: Int, limit: Int): Page\u003CUser>\n    suspend fun search(query: String): List\u003CUser>\n    suspend fun create(request: CreateUserRequest): User\n    suspend fun update(id: UUID, request: UpdateUserRequest): User?\n    suspend fun delete(id: UUID): Boolean\n    suspend fun count(): Long\n}\n```\n\n### Exposed Implementation\n\n```kotlin\nclass ExposedUserRepository(\n    private val database: Database,\n) : UserRepository {\n\n    override suspend fun findById(id: UUID): User? =\n        newSuspendedTransaction(db = database) {\n            UsersTable.selectAll()\n                .where { UsersTable.id eq id }\n                .map { it.toUser() }\n                .singleOrNull()\n        }\n\n    override suspend fun findByEmail(email: String): User? =\n        newSuspendedTransaction(db = database) {\n            UsersTable.selectAll()\n                .where { UsersTable.email eq email }\n                .map { it.toUser() }\n                .singleOrNull()\n        }\n\n    override suspend fun findAll(page: Int, limit: Int): Page\u003CUser> =\n        newSuspendedTransaction(db = database) {\n            val total = UsersTable.selectAll().count()\n            val data = UsersTable.selectAll()\n                .orderBy(UsersTable.createdAt, SortOrder.DESC)\n                .limit(limit)\n                .offset(((page - 1) * limit).toLong())\n                .map { it.toUser() }\n            Page(data = data, total = total, page = page, limit = limit)\n        }\n\n    override suspend fun search(query: String): List\u003CUser> =\n        newSuspendedTransaction(db = database) {\n            val sanitized = escapeLikePattern(query.lowercase())\n            UsersTable.selectAll()\n                .where {\n                    (UsersTable.name.lowerCase() like \"%${sanitized}%\") or\n                        (UsersTable.email.lowerCase() like \"%${sanitized}%\")\n                }\n                .orderBy(UsersTable.name)\n                .map { it.toUser() }\n        }\n\n    override suspend fun create(request: CreateUserRequest): User =\n        newSuspendedTransaction(db = database) {\n            UsersTable.insert {\n                it[name] = request.name\n                it[email] = request.email\n                it[role] = request.role\n            }.resultedValues!!.first().toUser()\n        }\n\n    override suspend fun update(id: UUID, request: UpdateUserRequest): User? =\n        newSuspendedTransaction(db = database) {\n            val updated = UsersTable.update({ UsersTable.id eq id }) {\n                request.name?.let { name -> it[UsersTable.name] = name }\n                request.email?.let { email -> it[UsersTable.email] = email }\n                it[updatedAt] = CurrentTimestampWithTimeZone\n            }\n            if (updated > 0) findById(id) else null\n        }\n\n    override suspend fun delete(id: UUID): Boolean =\n        newSuspendedTransaction(db = database) {\n            UsersTable.deleteWhere { UsersTable.id eq id } > 0\n        }\n\n    override suspend fun count(): Long =\n        newSuspendedTransaction(db = database) {\n            UsersTable.selectAll().count()\n        }\n\n    private fun ResultRow.toUser() = User(\n        id = this[UsersTable.id].value,\n        name = this[UsersTable.name],\n        email = this[UsersTable.email],\n        role = this[UsersTable.role],\n        metadata = this[UsersTable.metadata],\n        createdAt = this[UsersTable.createdAt],\n        updatedAt = this[UsersTable.updatedAt],\n    )\n}\n```\n\n## JSON Columns\n\n### JSONB with kotlinx.serialization\n\n```kotlin\n\u002F\u002F Custom column type for JSONB\ninline fun \u003Creified T : Any> Table.jsonb(\n    name: String,\n    json: Json,\n): Column\u003CT> = registerColumn(name, object : ColumnType\u003CT>() {\n    override fun sqlType() = \"JSONB\"\n\n    override fun valueFromDB(value: Any): T = when (value) {\n        is String -> json.decodeFromString(value)\n        is PGobject -> {\n            val jsonString = value.value\n                ?: throw IllegalArgumentException(\"PGobject value is null for column '$name'\")\n            json.decodeFromString(jsonString)\n        }\n        else -> throw IllegalArgumentException(\"Unexpected value: $value\")\n    }\n\n    override fun notNullValueToDB(value: T): Any =\n        PGobject().apply {\n            type = \"jsonb\"\n            this.value = json.encodeToString(value)\n        }\n})\n\n\u002F\u002F Usage in table\n@Serializable\ndata class UserMetadata(\n    val preferences: Map\u003CString, String> = emptyMap(),\n    val tags: List\u003CString> = emptyList(),\n)\n\nobject UsersTable : UUIDTable(\"users\") {\n    val metadata = jsonb\u003CUserMetadata>(\"metadata\", Json.Default).nullable()\n}\n```\n\n## Testing with Exposed\n\n### In-Memory Database for Tests\n\n```kotlin\nclass UserRepositoryTest : FunSpec({\n    lateinit var database: Database\n    lateinit var repository: UserRepository\n\n    beforeSpec {\n        database = Database.connect(\n            url = \"jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=PostgreSQL\",\n            driver = \"org.h2.Driver\",\n        )\n        transaction(database) {\n            SchemaUtils.create(UsersTable)\n        }\n        repository = ExposedUserRepository(database)\n    }\n\n    beforeTest {\n        transaction(database) {\n            UsersTable.deleteAll()\n        }\n    }\n\n    test(\"create and find user\") {\n        val user = repository.create(CreateUserRequest(\"Alice\", \"alice@example.com\"))\n\n        user.name shouldBe \"Alice\"\n        user.email shouldBe \"alice@example.com\"\n\n        val found = repository.findById(user.id)\n        found shouldBe user\n    }\n\n    test(\"findByEmail returns null for unknown email\") {\n        val result = repository.findByEmail(\"unknown@example.com\")\n        result.shouldBeNull()\n    }\n\n    test(\"pagination works correctly\") {\n        repeat(25) { i ->\n            repository.create(CreateUserRequest(\"User $i\", \"user$i@example.com\"))\n        }\n\n        val page1 = repository.findAll(page = 1, limit = 10)\n        page1.data shouldHaveSize 10\n        page1.total shouldBe 25\n        page1.hasNext shouldBe true\n\n        val page3 = repository.findAll(page = 3, limit = 10)\n        page3.data shouldHaveSize 5\n        page3.hasNext shouldBe false\n    }\n})\n```\n\n## Gradle Dependencies\n\n```kotlin\n\u002F\u002F build.gradle.kts\ndependencies {\n    \u002F\u002F Exposed\n    implementation(\"org.jetbrains.exposed:exposed-core:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-dao:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-jdbc:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-kotlin-datetime:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-json:1.0.0\")\n\n    \u002F\u002F Database driver\n    implementation(\"org.postgresql:postgresql:42.7.5\")\n\n    \u002F\u002F Connection pooling\n    implementation(\"com.zaxxer:HikariCP:6.2.1\")\n\n    \u002F\u002F Migrations\n    implementation(\"org.flywaydb:flyway-core:10.22.0\")\n    implementation(\"org.flywaydb:flyway-database-postgresql:10.22.0\")\n\n    \u002F\u002F Testing\n    testImplementation(\"com.h2database:h2:2.3.232\")\n}\n```\n\n## Quick Reference: Exposed Patterns\n\n| Pattern | Description |\n|---------|-------------|\n| `object Table : UUIDTable(\"name\")` | Define table with UUID primary key |\n| `newSuspendedTransaction { }` | Coroutine-safe transaction block |\n| `Table.selectAll().where { }` | Query with conditions |\n| `Table.insertAndGetId { }` | Insert and return generated ID |\n| `Table.update({ condition }) { }` | Update matching rows |\n| `Table.deleteWhere { }` | Delete matching rows |\n| `Table.batchInsert(items) { }` | Efficient bulk insert |\n| `innerJoin` \u002F `leftJoin` | Join tables |\n| `orderBy` \u002F `limit` \u002F `offset` | Sort and paginate |\n| `count()` \u002F `sum()` \u002F `avg()` | Aggregation functions |\n\n**Remember**: Use the DSL style for simple queries and the DAO style when you need entity lifecycle management. Always use `newSuspendedTransaction` for coroutine support, and wrap database operations behind a repository interface for testability.\n","# Kotlin Exposed Patterns\n\nComprehensive patterns for database access with JetBrains Exposed ORM, including DSL queries, DAO, transactions, and production-ready configuration.\n\n## When to Use\n\n- Setting up database access with Exposed\n- Writing SQL queries using Exposed DSL or DAO\n- Configuring connection pooling with HikariCP\n- Creating database migrations with Flyway\n- Implementing the repository pattern with Exposed\n- Handling JSON columns and complex queries\n\n## How It Works\n\nExposed provides two query styles: DSL for direct SQL-like expressions and DAO for entity lifecycle management. HikariCP manages a pool of reusable database connections configured via `HikariConfig`. Flyway runs versioned SQL migration scripts at startup to keep the schema in sync. All database operations run inside `newSuspendedTransaction` blocks for coroutine safety and atomicity. The repository pattern wraps Exposed queries behind an interface so business logic stays decoupled from the data layer and tests can use an in-memory H2 database.\n\n## Examples\n\n### DSL Query\n\n```kotlin\nsuspend fun findUserById(id: UUID): UserRow? =\n    newSuspendedTransaction {\n        UsersTable.selectAll()\n            .where { UsersTable.id eq id }\n            .map { it.toUser() }\n            .singleOrNull()\n    }\n```\n\n### DAO Entity Usage\n\n```kotlin\nsuspend fun createUser(request: CreateUserRequest): User =\n    newSuspendedTransaction {\n        UserEntity.new {\n            name = request.name\n            email = request.email\n            role = request.role\n        }.toModel()\n    }\n```\n\n### HikariCP Configuration\n\n```kotlin\nval hikariConfig = HikariConfig().apply {\n    driverClassName = config.driver\n    jdbcUrl = config.url\n    username = config.username\n    password = config.password\n    maximumPoolSize = config.maxPoolSize\n    isAutoCommit = false\n    transactionIsolation = \"TRANSACTION_READ_COMMITTED\"\n    validate()\n}\n```\n\n## Database Setup\n\n### HikariCP Connection Pooling\n\n```kotlin\n\u002F\u002F DatabaseFactory.kt\nobject DatabaseFactory {\n    fun create(config: DatabaseConfig): Database {\n        val hikariConfig = HikariConfig().apply {\n            driverClassName = config.driver\n            jdbcUrl = config.url\n            username = config.username\n            password = config.password\n            maximumPoolSize = config.maxPoolSize\n            isAutoCommit = false\n            transactionIsolation = \"TRANSACTION_READ_COMMITTED\"\n            validate()\n        }\n\n        return Database.connect(HikariDataSource(hikariConfig))\n    }\n}\n\ndata class DatabaseConfig(\n    val url: String,\n    val driver: String = \"org.postgresql.Driver\",\n    val username: String = \"\",\n    val password: String = \"\",\n    val maxPoolSize: Int = 10,\n)\n```\n\n### Flyway Migrations\n\n```kotlin\n\u002F\u002F FlywayMigration.kt\nfun runMigrations(config: DatabaseConfig) {\n    Flyway.configure()\n        .dataSource(config.url, config.username, config.password)\n        .locations(\"classpath:db\u002Fmigration\")\n        .baselineOnMigrate(true)\n        .load()\n        .migrate()\n}\n\n\u002F\u002F Application startup\nfun Application.module() {\n    val config = DatabaseConfig(\n        url = environment.config.property(\"database.url\").getString(),\n        username = environment.config.property(\"database.username\").getString(),\n        password = environment.config.property(\"database.password\").getString(),\n    )\n    runMigrations(config)\n    val database = DatabaseFactory.create(config)\n    \u002F\u002F ...\n}\n```\n\n### Migration Files\n\n```sql\n-- src\u002Fmain\u002Fresources\u002Fdb\u002Fmigration\u002FV1__create_users.sql\nCREATE TABLE users (\n    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n    name VARCHAR(100) NOT NULL,\n    email VARCHAR(255) NOT NULL UNIQUE,\n    role VARCHAR(20) NOT NULL DEFAULT 'USER',\n    metadata JSONB,\n    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n);\n\nCREATE INDEX idx_users_email ON users(email);\nCREATE INDEX idx_users_role ON users(role);\n```\n\n## Table Definitions\n\n### DSL Style Tables\n\n```kotlin\n\u002F\u002F tables\u002FUsersTable.kt\nobject UsersTable : UUIDTable(\"users\") {\n    val name = varchar(\"name\", 100)\n    val email = varchar(\"email\", 255).uniqueIndex()\n    val role = enumerationByName\u003CRole>(\"role\", 20)\n    val metadata = jsonb\u003CUserMetadata>(\"metadata\", Json.Default).nullable()\n    val createdAt = timestampWithTimeZone(\"created_at\").defaultExpression(CurrentTimestampWithTimeZone)\n    val updatedAt = timestampWithTimeZone(\"updated_at\").defaultExpression(CurrentTimestampWithTimeZone)\n}\n\nobject OrdersTable : UUIDTable(\"orders\") {\n    val userId = uuid(\"user_id\").references(UsersTable.id)\n    val status = enumerationByName\u003COrderStatus>(\"status\", 20)\n    val totalAmount = long(\"total_amount\")\n    val currency = varchar(\"currency\", 3)\n    val createdAt = timestampWithTimeZone(\"created_at\").defaultExpression(CurrentTimestampWithTimeZone)\n}\n\nobject OrderItemsTable : UUIDTable(\"order_items\") {\n    val orderId = uuid(\"order_id\").references(OrdersTable.id, onDelete = ReferenceOption.CASCADE)\n    val productId = uuid(\"product_id\")\n    val quantity = integer(\"quantity\")\n    val unitPrice = long(\"unit_price\")\n}\n```\n\n### Composite Tables\n\n```kotlin\nobject UserRolesTable : Table(\"user_roles\") {\n    val userId = uuid(\"user_id\").references(UsersTable.id, onDelete = ReferenceOption.CASCADE)\n    val roleId = uuid(\"role_id\").references(RolesTable.id, onDelete = ReferenceOption.CASCADE)\n    override val primaryKey = PrimaryKey(userId, roleId)\n}\n```\n\n## DSL Queries\n\n### Basic CRUD\n\n```kotlin\n\u002F\u002F Insert\nsuspend fun insertUser(name: String, email: String, role: Role): UUID =\n    newSuspendedTransaction {\n        UsersTable.insertAndGetId {\n            it[UsersTable.name] = name\n            it[UsersTable.email] = email\n            it[UsersTable.role] = role\n        }.value\n    }\n\n\u002F\u002F Select by ID\nsuspend fun findUserById(id: UUID): UserRow? =\n    newSuspendedTransaction {\n        UsersTable.selectAll()\n            .where { UsersTable.id eq id }\n            .map { it.toUser() }\n            .singleOrNull()\n    }\n\n\u002F\u002F Select with conditions\nsuspend fun findActiveAdmins(): List\u003CUserRow> =\n    newSuspendedTransaction {\n        UsersTable.selectAll()\n            .where { (UsersTable.role eq Role.ADMIN) }\n            .orderBy(UsersTable.name)\n            .map { it.toUser() }\n    }\n\n\u002F\u002F Update\nsuspend fun updateUserEmail(id: UUID, newEmail: String): Boolean =\n    newSuspendedTransaction {\n        UsersTable.update({ UsersTable.id eq id }) {\n            it[email] = newEmail\n            it[updatedAt] = CurrentTimestampWithTimeZone\n        } > 0\n    }\n\n\u002F\u002F Delete\nsuspend fun deleteUser(id: UUID): Boolean =\n    newSuspendedTransaction {\n        UsersTable.deleteWhere { UsersTable.id eq id } > 0\n    }\n\n\u002F\u002F Row mapping\nprivate fun ResultRow.toUser() = UserRow(\n    id = this[UsersTable.id].value,\n    name = this[UsersTable.name],\n    email = this[UsersTable.email],\n    role = this[UsersTable.role],\n    metadata = this[UsersTable.metadata],\n    createdAt = this[UsersTable.createdAt],\n    updatedAt = this[UsersTable.updatedAt],\n)\n```\n\n### Advanced Queries\n\n```kotlin\n\u002F\u002F Join queries\nsuspend fun findOrdersWithUser(userId: UUID): List\u003COrderWithUser> =\n    newSuspendedTransaction {\n        (OrdersTable innerJoin UsersTable)\n            .selectAll()\n            .where { OrdersTable.userId eq userId }\n            .orderBy(OrdersTable.createdAt, SortOrder.DESC)\n            .map { row ->\n                OrderWithUser(\n                    orderId = row[OrdersTable.id].value,\n                    status = row[OrdersTable.status],\n                    totalAmount = row[OrdersTable.totalAmount],\n                    userName = row[UsersTable.name],\n                )\n            }\n    }\n\n\u002F\u002F Aggregation\nsuspend fun countUsersByRole(): Map\u003CRole, Long> =\n    newSuspendedTransaction {\n        UsersTable\n            .select(UsersTable.role, UsersTable.id.count())\n            .groupBy(UsersTable.role)\n            .associate { row ->\n                row[UsersTable.role] to row[UsersTable.id.count()]\n            }\n    }\n\n\u002F\u002F Subqueries\nsuspend fun findUsersWithOrders(): List\u003CUserRow> =\n    newSuspendedTransaction {\n        UsersTable.selectAll()\n            .where {\n                UsersTable.id inSubQuery\n                    OrdersTable.select(OrdersTable.userId).withDistinct()\n            }\n            .map { it.toUser() }\n    }\n\n\u002F\u002F LIKE and pattern matching — always escape user input to prevent wildcard injection\nprivate fun escapeLikePattern(input: String): String =\n    input.replace(\"\\\\\", \"\\\\\\\\\").replace(\"%\", \"\\\\%\").replace(\"_\", \"\\\\_\")\n\nsuspend fun searchUsers(query: String): List\u003CUserRow> =\n    newSuspendedTransaction {\n        val sanitized = escapeLikePattern(query.lowercase())\n        UsersTable.selectAll()\n            .where {\n                (UsersTable.name.lowerCase() like \"%${sanitized}%\") or\n                    (UsersTable.email.lowerCase() like \"%${sanitized}%\")\n            }\n            .map { it.toUser() }\n    }\n```\n\n### Pagination\n\n```kotlin\ndata class Page\u003CT>(\n    val data: List\u003CT>,\n    val total: Long,\n    val page: Int,\n    val limit: Int,\n) {\n    val totalPages: Int get() = ((total + limit - 1) \u002F limit).toInt()\n    val hasNext: Boolean get() = page \u003C totalPages\n    val hasPrevious: Boolean get() = page > 1\n}\n\nsuspend fun findUsersPaginated(page: Int, limit: Int): Page\u003CUserRow> =\n    newSuspendedTransaction {\n        val total = UsersTable.selectAll().count()\n        val data = UsersTable.selectAll()\n            .orderBy(UsersTable.createdAt, SortOrder.DESC)\n            .limit(limit)\n            .offset(((page - 1) * limit).toLong())\n            .map { it.toUser() }\n\n        Page(data = data, total = total, page = page, limit = limit)\n    }\n```\n\n### Batch Operations\n\n```kotlin\n\u002F\u002F Batch insert\nsuspend fun insertUsers(users: List\u003CCreateUserRequest>): List\u003CUUID> =\n    newSuspendedTransaction {\n        UsersTable.batchInsert(users) { user ->\n            this[UsersTable.name] = user.name\n            this[UsersTable.email] = user.email\n            this[UsersTable.role] = user.role\n        }.map { it[UsersTable.id].value }\n    }\n\n\u002F\u002F Upsert (insert or update on conflict)\nsuspend fun upsertUser(id: UUID, name: String, email: String) {\n    newSuspendedTransaction {\n        UsersTable.upsert(UsersTable.email) {\n            it[UsersTable.id] = EntityID(id, UsersTable)\n            it[UsersTable.name] = name\n            it[UsersTable.email] = email\n            it[updatedAt] = CurrentTimestampWithTimeZone\n        }\n    }\n}\n```\n\n## DAO Pattern\n\n### Entity Definitions\n\n```kotlin\n\u002F\u002F entities\u002FUserEntity.kt\nclass UserEntity(id: EntityID\u003CUUID>) : UUIDEntity(id) {\n    companion object : UUIDEntityClass\u003CUserEntity>(UsersTable)\n\n    var name by UsersTable.name\n    var email by UsersTable.email\n    var role by UsersTable.role\n    var metadata by UsersTable.metadata\n    var createdAt by UsersTable.createdAt\n    var updatedAt by UsersTable.updatedAt\n\n    val orders by OrderEntity referrersOn OrdersTable.userId\n\n    fun toModel(): User = User(\n        id = id.value,\n        name = name,\n        email = email,\n        role = role,\n        metadata = metadata,\n        createdAt = createdAt,\n        updatedAt = updatedAt,\n    )\n}\n\nclass OrderEntity(id: EntityID\u003CUUID>) : UUIDEntity(id) {\n    companion object : UUIDEntityClass\u003COrderEntity>(OrdersTable)\n\n    var user by UserEntity referencedOn OrdersTable.userId\n    var status by OrdersTable.status\n    var totalAmount by OrdersTable.totalAmount\n    var currency by OrdersTable.currency\n    var createdAt by OrdersTable.createdAt\n\n    val items by OrderItemEntity referrersOn OrderItemsTable.orderId\n}\n```\n\n### DAO Operations\n\n```kotlin\nsuspend fun findUserByEmail(email: String): User? =\n    newSuspendedTransaction {\n        UserEntity.find { UsersTable.email eq email }\n            .firstOrNull()\n            ?.toModel()\n    }\n\nsuspend fun createUser(request: CreateUserRequest): User =\n    newSuspendedTransaction {\n        UserEntity.new {\n            name = request.name\n            email = request.email\n            role = request.role\n        }.toModel()\n    }\n\nsuspend fun updateUser(id: UUID, request: UpdateUserRequest): User? =\n    newSuspendedTransaction {\n        UserEntity.findById(id)?.apply {\n            request.name?.let { name = it }\n            request.email?.let { email = it }\n            updatedAt = OffsetDateTime.now(ZoneOffset.UTC)\n        }?.toModel()\n    }\n```\n\n## Transactions\n\n### Suspend Transaction Support\n\n```kotlin\n\u002F\u002F Good: Use newSuspendedTransaction for coroutine support\nsuspend fun performDatabaseOperation(): Result\u003CUser> =\n    runCatching {\n        newSuspendedTransaction {\n            val user = UserEntity.new {\n                name = \"Alice\"\n                email = \"alice@example.com\"\n            }\n            \u002F\u002F All operations in this block are atomic\n            user.toModel()\n        }\n    }\n\n\u002F\u002F Good: Nested transactions with savepoints\nsuspend fun transferFunds(fromId: UUID, toId: UUID, amount: Long) {\n    newSuspendedTransaction {\n        val from = UserEntity.findById(fromId) ?: throw NotFoundException(\"User $fromId not found\")\n        val to = UserEntity.findById(toId) ?: throw NotFoundException(\"User $toId not found\")\n\n        \u002F\u002F Debit\n        from.balance -= amount\n        \u002F\u002F Credit\n        to.balance += amount\n\n        \u002F\u002F Both succeed or both fail\n    }\n}\n```\n\n### Transaction Isolation\n\n```kotlin\nsuspend fun readCommittedQuery(): List\u003CUser> =\n    newSuspendedTransaction(transactionIsolation = Connection.TRANSACTION_READ_COMMITTED) {\n        UserEntity.all().map { it.toModel() }\n    }\n\nsuspend fun serializableOperation() {\n    newSuspendedTransaction(transactionIsolation = Connection.TRANSACTION_SERIALIZABLE) {\n        \u002F\u002F Strictest isolation level for critical operations\n    }\n}\n```\n\n## Repository Pattern\n\n### Interface Definition\n\n```kotlin\ninterface UserRepository {\n    suspend fun findById(id: UUID): User?\n    suspend fun findByEmail(email: String): User?\n    suspend fun findAll(page: Int, limit: Int): Page\u003CUser>\n    suspend fun search(query: String): List\u003CUser>\n    suspend fun create(request: CreateUserRequest): User\n    suspend fun update(id: UUID, request: UpdateUserRequest): User?\n    suspend fun delete(id: UUID): Boolean\n    suspend fun count(): Long\n}\n```\n\n### Exposed Implementation\n\n```kotlin\nclass ExposedUserRepository(\n    private val database: Database,\n) : UserRepository {\n\n    override suspend fun findById(id: UUID): User? =\n        newSuspendedTransaction(db = database) {\n            UsersTable.selectAll()\n                .where { UsersTable.id eq id }\n                .map { it.toUser() }\n                .singleOrNull()\n        }\n\n    override suspend fun findByEmail(email: String): User? =\n        newSuspendedTransaction(db = database) {\n            UsersTable.selectAll()\n                .where { UsersTable.email eq email }\n                .map { it.toUser() }\n                .singleOrNull()\n        }\n\n    override suspend fun findAll(page: Int, limit: Int): Page\u003CUser> =\n        newSuspendedTransaction(db = database) {\n            val total = UsersTable.selectAll().count()\n            val data = UsersTable.selectAll()\n                .orderBy(UsersTable.createdAt, SortOrder.DESC)\n                .limit(limit)\n                .offset(((page - 1) * limit).toLong())\n                .map { it.toUser() }\n            Page(data = data, total = total, page = page, limit = limit)\n        }\n\n    override suspend fun search(query: String): List\u003CUser> =\n        newSuspendedTransaction(db = database) {\n            val sanitized = escapeLikePattern(query.lowercase())\n            UsersTable.selectAll()\n                .where {\n                    (UsersTable.name.lowerCase() like \"%${sanitized}%\") or\n                        (UsersTable.email.lowerCase() like \"%${sanitized}%\")\n                }\n                .orderBy(UsersTable.name)\n                .map { it.toUser() }\n        }\n\n    override suspend fun create(request: CreateUserRequest): User =\n        newSuspendedTransaction(db = database) {\n            UsersTable.insert {\n                it[name] = request.name\n                it[email] = request.email\n                it[role] = request.role\n            }.resultedValues!!.first().toUser()\n        }\n\n    override suspend fun update(id: UUID, request: UpdateUserRequest): User? =\n        newSuspendedTransaction(db = database) {\n            val updated = UsersTable.update({ UsersTable.id eq id }) {\n                request.name?.let { name -> it[UsersTable.name] = name }\n                request.email?.let { email -> it[UsersTable.email] = email }\n                it[updatedAt] = CurrentTimestampWithTimeZone\n            }\n            if (updated > 0) findById(id) else null\n        }\n\n    override suspend fun delete(id: UUID): Boolean =\n        newSuspendedTransaction(db = database) {\n            UsersTable.deleteWhere { UsersTable.id eq id } > 0\n        }\n\n    override suspend fun count(): Long =\n        newSuspendedTransaction(db = database) {\n            UsersTable.selectAll().count()\n        }\n\n    private fun ResultRow.toUser() = User(\n        id = this[UsersTable.id].value,\n        name = this[UsersTable.name],\n        email = this[UsersTable.email],\n        role = this[UsersTable.role],\n        metadata = this[UsersTable.metadata],\n        createdAt = this[UsersTable.createdAt],\n        updatedAt = this[UsersTable.updatedAt],\n    )\n}\n```\n\n## JSON Columns\n\n### JSONB with kotlinx.serialization\n\n```kotlin\n\u002F\u002F Custom column type for JSONB\ninline fun \u003Creified T : Any> Table.jsonb(\n    name: String,\n    json: Json,\n): Column\u003CT> = registerColumn(name, object : ColumnType\u003CT>() {\n    override fun sqlType() = \"JSONB\"\n\n    override fun valueFromDB(value: Any): T = when (value) {\n        is String -> json.decodeFromString(value)\n        is PGobject -> {\n            val jsonString = value.value\n                ?: throw IllegalArgumentException(\"PGobject value is null for column '$name'\")\n            json.decodeFromString(jsonString)\n        }\n        else -> throw IllegalArgumentException(\"Unexpected value: $value\")\n    }\n\n    override fun notNullValueToDB(value: T): Any =\n        PGobject().apply {\n            type = \"jsonb\"\n            this.value = json.encodeToString(value)\n        }\n})\n\n\u002F\u002F Usage in table\n@Serializable\ndata class UserMetadata(\n    val preferences: Map\u003CString, String> = emptyMap(),\n    val tags: List\u003CString> = emptyList(),\n)\n\nobject UsersTable : UUIDTable(\"users\") {\n    val metadata = jsonb\u003CUserMetadata>(\"metadata\", Json.Default).nullable()\n}\n```\n\n## Testing with Exposed\n\n### In-Memory Database for Tests\n\n```kotlin\nclass UserRepositoryTest : FunSpec({\n    lateinit var database: Database\n    lateinit var repository: UserRepository\n\n    beforeSpec {\n        database = Database.connect(\n            url = \"jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=PostgreSQL\",\n            driver = \"org.h2.Driver\",\n        )\n        transaction(database) {\n            SchemaUtils.create(UsersTable)\n        }\n        repository = ExposedUserRepository(database)\n    }\n\n    beforeTest {\n        transaction(database) {\n            UsersTable.deleteAll()\n        }\n    }\n\n    test(\"create and find user\") {\n        val user = repository.create(CreateUserRequest(\"Alice\", \"alice@example.com\"))\n\n        user.name shouldBe \"Alice\"\n        user.email shouldBe \"alice@example.com\"\n\n        val found = repository.findById(user.id)\n        found shouldBe user\n    }\n\n    test(\"findByEmail returns null for unknown email\") {\n        val result = repository.findByEmail(\"unknown@example.com\")\n        result.shouldBeNull()\n    }\n\n    test(\"pagination works correctly\") {\n        repeat(25) { i ->\n            repository.create(CreateUserRequest(\"User $i\", \"user$i@example.com\"))\n        }\n\n        val page1 = repository.findAll(page = 1, limit = 10)\n        page1.data shouldHaveSize 10\n        page1.total shouldBe 25\n        page1.hasNext shouldBe true\n\n        val page3 = repository.findAll(page = 3, limit = 10)\n        page3.data shouldHaveSize 5\n        page3.hasNext shouldBe false\n    }\n})\n```\n\n## Gradle Dependencies\n\n```kotlin\n\u002F\u002F build.gradle.kts\ndependencies {\n    \u002F\u002F Exposed\n    implementation(\"org.jetbrains.exposed:exposed-core:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-dao:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-jdbc:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-kotlin-datetime:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-json:1.0.0\")\n\n    \u002F\u002F Database driver\n    implementation(\"org.postgresql:postgresql:42.7.5\")\n\n    \u002F\u002F Connection pooling\n    implementation(\"com.zaxxer:HikariCP:6.2.1\")\n\n    \u002F\u002F Migrations\n    implementation(\"org.flywaydb:flyway-core:10.22.0\")\n    implementation(\"org.flywaydb:flyway-database-postgresql:10.22.0\")\n\n    \u002F\u002F Testing\n    testImplementation(\"com.h2database:h2:2.3.232\")\n}\n```\n\n## Quick Reference: Exposed Patterns\n\n| Pattern | Description |\n|---------|-------------|\n| `object Table : UUIDTable(\"name\")` | Define table with UUID primary key |\n| `newSuspendedTransaction { }` | Coroutine-safe transaction block |\n| `Table.selectAll().where { }` | Query with conditions |\n| `Table.insertAndGetId { }` | Insert and return generated ID |\n| `Table.update({ condition }) { }` | Update matching rows |\n| `Table.deleteWhere { }` | Delete matching rows |\n| `Table.batchInsert(items) { }` | Efficient bulk insert |\n| `innerJoin` \u002F `leftJoin` | Join tables |\n| `orderBy` \u002F `limit` \u002F `offset` | Sort and paginate |\n| `count()` \u002F `sum()` \u002F `avg()` | Aggregation functions |\n\n**Remember**: Use the DSL style for simple queries and the DAO style when you need entity lifecycle management. Always use `newSuspendedTransaction` for coroutine support, and wrap database operations behind a repository interface for testability.\n",{"name":5,"origin":23,"description":7},"ECC","main","f37de8f681f0c0ca0e0ebab6e5fddf764ca7553d","skills\u002Fkotlin-exposed-patterns",1,"https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one","https:\u002F\u002Fagisota.github.io\u002Fold-one\u002F","https:\u002F\u002Fgithub.com\u002Fagisota","pzd.world","2026-07-04 22:32:06",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add agisota\u002Fold-one --skill kotlin-exposed-patterns",{"tool":39,"command":40},"bunx","bunx skills add agisota\u002Fold-one --skill kotlin-exposed-patterns",{"tool":42,"command":43},"pnpm","pnpm dlx skills add agisota\u002Fold-one --skill kotlin-exposed-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fkotlin-exposed-patterns\u002FSKILL.md",true,[],[48,55,62,71,78,85],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":18},"01M75KRGZWQWE9JDBS6RX42NWV","zoom-out","Tell the agent to zoom out and give broader context or a higher-level perspective. Use when you're unfamiliar with a section of code or need to understand how it fits into the bigger picture.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fzoom-out\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M75KRCZHKE0ZYAQFFYHS0YNP","zeroize-audit","Detects missing zeroization of sensitive data in source code and identifies zeroization removed by compiler optimizations, with assembly-level analysis, and control-flow verification. Use for auditing C\u002FC++\u002FRust code handling secrets, keys, passwords, or other sensitive data.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fzeroize-audit\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":67,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":18},"01M75KR94KYQ30DTE1P9WNDAE0","yeet","Use only when the user explicitly asks to stage, commit, push, and open a GitHub pull request in one flow using the GitHub CLI (`gh`).","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":18},"01M75KR3H13YJ9QHMD49818FA1","yara-rule-authoring","Guides authoring of high-quality YARA-X detection rules for malware identification. Use when writing, reviewing, or optimizing YARA rules. Covers naming conventions, string selection, performance optimization, migration from legacy YARA, and false positive reduction. Triggers on: YARA, YARA-X, malware detection, threat hunting, IOC, signature, crx module, dex module.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fyara-rule-authoring\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":18},"01M75KQMPY8A4Y8XTDD2DT0M9T","x-twitter-growth","X\u002FTwitter growth engine for building audience, crafting viral content, and analyzing engagement. Use when the user wants to grow on X\u002FTwitter, write tweets or threads, analyze their X profile, research competitors on X, plan a posting strategy, or optimize engagement. Complements social-content (generic multi-platform) with X-specific depth: algorithm mechanics, thread engineering, reply strategy, profile optimization, and competitive intelligence via web search.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fx-twitter-growth\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":18},"01M75KQHNZ0ANZNJGZY6M8MDAK","x-api","X\u002FTwitter API integration for posting tweets, threads, reading timelines, search, and analytics. Covers OAuth auth patterns, rate limits, and platform-native content posting. Use when the user wants to interact with X programmatically.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fx-api\u002FSKILL.md",[],[]]