CRUD Operations

AN5 ORM provides a clean, type-safe API for all CRUD operations tailored for Kotlin.


Client Setup

import an5.client.An5Db
import an5.client.An5Orm
import an5.client.User

val db = An5Db(System.getenv("DATABASE_URL"))

An5Db implements AutoCloseable; An5Db(url).use { db -> ... } closes it when the block returns.


1. Create

Create a Single Record

val user = db.user.create(User(email = "john@example.com", name = "John Doe"))
println(user.id)

Create Many Records

val created = db.user.createMany(listOf(
    User(email = "alice@example.com", name = "Alice"),
    User(email = "bob@example.com", name = "Bob"),
))
println("Created $created users")

skipDuplicates defaults to false.


2. Read

Find by Primary Key or Unique Field

val user = db.user.findUnique(
    An5Orm.UserWhere(email = An5Orm.StringFilter.`is`("john@example.com")).build()
)

build() turns the typed where into the map the runtime reads; unset filters are left out of it.

Find Many Records with Filter & Sort

import an5.adapters.Sort

val users = db.user.findMany {
    where(
        An5Orm.UserWhere(
            isActive = An5Orm.BoolFilter.`is`(true),
            email = An5Orm.StringFilter.has("@example.com"),
        ).build()
    )
    orderBy("createdAt", Sort.DESC)
    skip(0)
    take(10)
}

findMany { ... } takes a QueryBuilder lambda, so the query reads top to bottom.


3. Update

Update Single Record

val id = checkNotNull(user.id) { "create did not return a generated id" }

val updated = db.user.update(
    An5Orm.UserWhere(id = An5Orm.StringFilter.`is`(id)).build(),
    User(name = "Johnny Doe"),
)

Every property of User is nullable and defaults to null, which is what keeps an unset column out of the statement.


4. Delete

Delete Single Record

val id = checkNotNull(user.id) { "create did not return a generated id" }

db.user.delete(An5Orm.UserWhere(id = An5Orm.StringFilter.`is`(id)).build())

deleteMany(where) returns how many rows went away.


Next Steps