https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
exposed
  • g

    Gustav Elmgren

    01/09/2023, 12:42 PM
    I see similar problems to: https://github.com/JetBrains/Exposed/issues/1264 and https://github.com/JetBrains/Exposed/issues/1360, they have been open since 2021. Is nested transactions not supported?
    • 1
    • 4
  • r

    Rodrigo Silva

    01/13/2023, 7:55 PM
    Hello, everyone. I'm having a coroutine problem, giving the following exception
    Exception in thread "main" kotlinx.coroutines.CoroutinesInternalError: Fatal exception in coroutines machinery for DispatchedContinuation[BlockingEventLoop@7ca48474, Continuation at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$suspendedTransactionAsyncInternal$1.invokeSuspend(Suspended.kt)@59f99ea]. Please read KDoc to 'handleFatalException' method and report this incident to maintainers
    • 1
    • 1
  • r

    Ryan Woodcock

    01/19/2023, 7:04 AM
    Hey all, I’ve been making an effort to help out with the gradle plugin for code generation and have submitted some PRs to the repo, specifically allow other datetime providers and fixing codegen issues with Flyway (the PrimaryKey import problem). Only posting here in case the conversation is better suited for slack than github https://github.com/JetBrains/exposed-intellij-plugin/pull/15
  • h

    Haruki

    01/26/2023, 5:08 PM
    Hello everyone, I am currently working on a full-stack web app using the tutorial found here: https://kotlinlang.org/docs/multiplatform-full-stack-app.html#include-kmongo-in-the-process. We have been using MongoDB and KMongo, but I am trying to replace MongoDB with Postgres DB and Kmongo with Exposed. As an example, using Kmongo, we have this code: val client = KMongo.createClient().coroutine val database = client.getDatabase("shoppingList") val collection = database.getCollection<ShoppingListItem>() get { call.respond(collection.find().toList()) } I am wondering if there is a way to do the same thing with Exposed. My current understanding is to create an object DatabaseFactory for setup in Server.kt, create a Table and then use select:
    object DatabaseFactory {
    fun init() {
    Database.connect(
    "jdbc:<postgresql://host>:port/5432",
    driver = "org.postgresql.Driver",
    user = "user",
    password = "password"
    )
    }
    }
    object ShoppingListItems: Table() {
    val id = integer("id").autoIncrement().primaryKey()
    val name = varchar("name", length = 255)
    val owners = varchar("owners", length = 255)
    }
    get {
    call.respond(ShoppingListItems.select { ShoppingListItems.owners like user }.toList())
    }
    I am also wondering if we need to create a table. Instead, I want to use a data class like this: val collection = database.getCollection<ShoppingListItem>(). Thank you in advance for your help!
  • m

    maxmello

    01/30/2023, 4:36 PM
    Are there any example projects where Exposed is used without everything being statically defined? So instead of
    object
    tables and
    (companion) object
    EntityClasses, have classes that are instantiated e.g. in ktor module on app start, which would give the ability to properly pass in dependencies instead of relying on global variables? For example, for my own extensions of Exposed for handling jsonb columns, I need to pass in a Jackson
    ObjectMapper
    . Right now, I have a global object where I set a var on application start, but the Exposed part is the only part of my ktor application not having dependencies properly passed in via constructor params (I don’t use any DI framework).
    r
    • 2
    • 5
  • p

    Pavel Naumov

    02/06/2023, 10:02 AM
    hello everyone, i'm stuck with .sum() aggregate function. I have a column of type ushort and i have a query which should retrieve a sum of the column values. Even though the values are ushort (SMALLINT UNSIGNED) resulted sum might be out of the ushort range. And for plain MariaDB query in console it's absolutely legit query. But
    MyTable.uShortCol.sum()
    truncates result to ushort, obviously. Any adwise? I've found an issue on the GitGub https://github.com/JetBrains/Exposed/issues/1035 which seems relevant to me but there's no solution
    s
    • 2
    • 4
  • a

    aazavoykin

    02/09/2023, 7:14 AM
    Hello, evenryone! I`m a novice with a little question: how could I create a table`s column with a check constraint between values of two columns like in the example (
    "limit" >= balance
    ):
    CREATE TABLE IF NOT EXISTS account (
      id          uuid PRIMARY KEY,
      balance     DECIMAL(16,2) NOT NULL DEFAULT 0 CHECK (balance >= 0),
      "limit"     DECIMAL(16,2) NOT NULL DEFAULT 0 CHECK ("limit" >= balance)
    );
    How could I get the current value of column here?
    object AccountTable : Table("account") {
    ...
    val limit: Column<BigDecimal> = decimal("limit", 16, 2)
        .default(BigDecimal.ZERO)
        .check {it.greaterEq(??????)}
    }
    s
    • 2
    • 2
  • g

    Goetz Markgraf

    02/10/2023, 2:32 PM
    Hello everyone. I am thinking of using exposed for the next customer project. Are there any experience of using it in the field? I mean, it’s version number is still 0.X and it is not supported by JetBrains but a staff project. Do you have any references to customers using exposed commercially / professionally?
    p
    a
    +2
    • 5
    • 14
  • s

    Shmulik Klein

    02/12/2023, 2:16 PM
    Hey all! does Exposed expose (🤭) any monitoring metrics i.e. connection timeouts, etc. out of the box? I have tried to find those in the code, but couldn't find any hint for that.
    p
    • 2
    • 2
  • e

    Endre Deak

    02/13/2023, 10:23 PM
    set the channel topic: https://github.com/jetbrains/exposed Some words around Exposed usage in prod: https://kotlinlang.slack.com/archives/C0CG7E0A1/p1661259081172889
  • l

    Lee Hayeon

    02/15/2023, 7:42 PM
    Inside the transaction, can I update the data immediately before the transaction ends? Or am I supposed to split transaction myself?
  • l

    Lee Hayeon

    02/15/2023, 7:46 PM
    Is it no-op to nest transactions by default?
  • m

    Mazhar Ibna Zahur

    02/16/2023, 7:26 AM
    can anyone give me a sort introduction how can i work with view table with exposed and ktor ?
    a
    • 2
    • 1
  • d

    dmcg

    02/17/2023, 11:31 AM
    PostgreSQL and Exposed - Kotlin database access

    https://youtu.be/Uza_dWsNMUs▾

  • d

    dmcg

    02/24/2023, 11:30 AM
    Using PostgreSQL as an Append-only Datastore with Kotlin and Exposed

    https://youtu.be/Madp0WGq2iA▾

  • m

    Martin Harvan

    02/25/2023, 11:21 PM
    HI, is it possible in the DAO api to transform multiple DB fields into a single DAO field? e.g. in DB I store
    portion
    (EARLY, MID, LATE) and
    month
    and I have data class for it and I would like the DAO to have such field instead of 2 fields
    a
    • 2
    • 1
  • d

    Dantin Kakkar

    02/28/2023, 5:20 PM
    Is anyone actively maintaining Exposed at this point? Would like to understand (given there are a number of issues and PRs pending)
    a
    p
    h
    • 4
    • 9
  • s

    Shreck Ye

    03/08/2023, 9:41 AM
    Hello, I added a benchmark portion in the TechEmpower Framework Benchmarks project to test the permance of Exposed DSL and DAO on top of the existing Ktor benchmark at https://github.com/TechEmpower/FrameworkBenchmarks/pull/7995. Maintainers and contributors please help me check if this is OK if you guys have time.
  • t

    T.J. Tarazevits

    03/09/2023, 6:39 PM
    Does Exposed have a way to stream records or batch fetch records for
    findAll()
    I am trying to process ~400k records in a cron-job and I don’t want to load all of them into memory at once. I’ve been googling for Kotlin Exposed Sequence or Kotlin Exposed Iterable but I am not sure if they actually only pull records on demand from postgres or if they just expose the result of the query as an Iterable
    s
    • 2
    • 1
  • w

    Wxffel

    03/16/2023, 5:22 PM
    Hello there! I am looking for help. We have created two IdTables (Boats and Customers) and their corresponding Classes to actually create new Entities in the database. Customers can rent a boat up to a date must return it after that. To keep track of these rents, we created a third Table called "Rents" which inherits from the "Table" class. BUT how do we create entities for that third table?
  • w

    Wxffel

    03/16/2023, 5:33 PM
    It is tricky for us because the primary key is not an int. It is a compound key which consists of the CustomerID and the BoatID. It looks like this in our code:
    object Rents : Table("T_Rents") {
        val customerId = reference("Customer_Id", Customers.id)
        val boatId = reference("Boat_Id", Boats.id)
        val dateOfRent = datetime("Date_of_rent")
        val dateOfReturn = datetime("Date_of_return")
    
        override val primaryKey = PrimaryKey(customerId, boatId, name = "CustomerAndBoatID")
    }
    How would we create an entity in this table?
    a
    p
    • 3
    • 3
  • w

    Wxffel

    03/16/2023, 6:33 PM
    We also face problems with auto-incrementation because we need it to work within a specified range of numbers like 1000-9999. At the moment we have a bad workaround which really is a scuffed auto incrementation implemented by ourselfs. It looks like this:
    integer("Customer_Id").check { it.between(1000, 9999) }.uniqueIndex().entityId().also {
        it.defaultValueFun = {
            val incrementId = (1000 + Customer.count() + 1).toInt()
            EntityIDFunctionProvider.createEntityID(incrementId, this)
        }
    }
    How would one use auto-incrementation within a specified range? I appreciate any help!
    a
    • 2
    • 4
  • a

    André Danielsson

    03/16/2023, 7:51 PM
    Hi 👋! We are building a feature where we are supposed to encrypt some specific column values and one detail is that we are supposed to have different encryption keys depending on the tenant that is doing the request. We have found two approaches that we are evaluating. Approach 1: We write a class implementing
    ColumnType
    that will be responsible for encryption and decryption when constructing the queries and returning results. We will need to create multiple instances, one per tenant, so that the appropriate encryption key is used. A snippet demonstrating this idea can be found here: https://pl.kotl.in/9azT-Jlr2 What we found is that this solution works when only using DSL but we are also using DAO to define relations and Entities are constructed by the Exposed library (using reflection?). To my knowledge there is no way of constructing Entities, passing our
    Table
    instances to it. This creates a problem for us as the codebase is using many DAOs today. Does anyone know if there is a way to get around that in any way and we can provide our own "factories" for creating
    Entity
    instances? Also, I sense that this approach is a bit “hacky” to depend on the tenant inside the DB layer. So this made us look into a second approach. Approach 2: We handle encryption/decryption in a repository. To make sure we can’t mix up what is encrypted and what is not we are introducing a new type for encrypted text and then writing a
    ColumnType
    for it to wrap/unwrap the type. We then move the responsibility for encryption/decryption to the repository. We will have different repository instances scoped to tenants so that they can fetch the appropriate encryption key. This is an example how it would look: https://pl.kotl.in/E0ewX3hZ9 This approach will introduce more boilerplate but in this case I think it's not too bad as we will get type safety and it will be impossible to confuse encrypted text with a String. 1. Which would you say is the best approach? 2. Is passing scoped repositories into the ColumnTypes the wrong abstraction and is it better to keep them as simple as possible?
    • 1
    • 1
  • m

    Manasseh

    03/19/2023, 8:28 PM
    Can someone please point me to a resource that explains FK relationships with exposed? For instance, I noticed there are multiple ways to declare relationships, so I'm a bit confused. I'd prefer to work with a standard way or something
  • d

    Daniel

    03/20/2023, 8:30 AM
    Hi, I am trying to use exposed DSL to simplify accessing legacy SQL server database that already exists. I need only read-only access to some of the complex tables and I was curious, do I need to define all of their columns to do that or can I specify only the ones I am interested in?
    b
    e
    s
    • 4
    • 6
  • m

    Manasseh

    03/20/2023, 10:45 AM
    If no resources, I'd appreciate if someone describes how to add many-to-many, many-to-one and one-to-one relationships in the model.
    e
    • 2
    • 2
  • g

    Gustav Elmgren

    03/22/2023, 8:39 AM
    We have some tables created with qoutes in postgres, thus case sensitive, but exposed seems to make the table name lowercase even if it is in quotes (https://github.com/JetBrains/Exposed/issues/1658), is there any existing workaround?
    s
    • 2
    • 4
  • d

    Daniel

    03/23/2023, 11:34 AM
    I have exposed code along the lines of this (names changed):
    private suspend fun <T> executeQuery(timeout: Duration = 3.seconds, block: suspend Transaction.() -> T): T =
    	withTimeout(timeout) { newSuspendedTransaction(<http://Dispatchers.IO|Dispatchers.IO>) { block() } }
    
    public suspend fun test1() = executeQuery(10.seconds) {
    	with(SomeTable) {
    		slice(id, other_id, valid_from).select {
    			(status eq BigDecimal.ONE) and (someFlag eq BigDecimal.ZERO) and
    			(CurrentDateTime.between(valid_from, valid_to))
    		}.forEach {
    			println("$it")
    		}
    	}
    }
    but I am getting
    Exception in thread "main" java.lang.IllegalStateException: Unexpected value: com.example.MayDatabase$SomeTable.valid_from of org.jetbrains.exposed.sql.Column
    I am not sure what I am doing wrong. Very similar code to this worked before
    b
    • 2
    • 6
  • d

    Daniel

    03/23/2023, 1:09 PM
    I have tried to add
    HASHBYTES
    as
    CustomFunction
    as this:
    class HashBytes(algo: Algo, input: Expression<*>) : CustomFunction<ExposedBlob?>("HASHBYTES", BlobColumnType(), QueryParameter(algo.algoName, TextColumnType()), input) {
            enum class Algo(val algoName: String) {
                MD2("MD2"),
                MD4("MD4"),
                MD5("MD5"),
                SHA("SHA"),
                SHA1("SHA1"),
                SHA256("SHA2_256"),
                SHA512("SHA2_512"),
            }
    }
    but when use I it in
    slice(someColumn, otherColumn, HashBytes(HashBytes.Algo.MD5, Concat("", someColumn, otherColumn)))
    I get the text representation of the hashbytes query in the results instead of the resulting value
  • e

    Eric Thomas

    03/29/2023, 10:10 PM
    Is it possible to store the raw Sql statements Exposed passes to the DB in a variable? I'm aware logging the statements via
    addLogger(StdOutSqlLogger)
    but how can I access/interact with this info? ex:
    Exposed: transaction { table.select { table.id eq 123 } }
    Raw SQL ran against DB: SELECT * FROM TABLE WHERE ID = 123;
    
    //desired result
    val executedSql = SELECT * FROM TABLE WHERE ID = 123;
    println(executedSql)
    How can I access the raw sql executed against the DB?
    a
    • 2
    • 4
Powered by Linen
Title
e

Eric Thomas

03/29/2023, 10:10 PM
Is it possible to store the raw Sql statements Exposed passes to the DB in a variable? I'm aware logging the statements via
addLogger(StdOutSqlLogger)
but how can I access/interact with this info? ex:
Exposed: transaction { table.select { table.id eq 123 } }
Raw SQL ran against DB: SELECT * FROM TABLE WHERE ID = 123;

//desired result
val executedSql = SELECT * FROM TABLE WHERE ID = 123;
println(executedSql)
How can I access the raw sql executed against the DB?
a

Alexey Soshin

03/30/2023, 11:52 AM
Hi Eric, You can do something like this:
transaction { 
    val rawSQL = table.select { table.id eq 123 }.prepareSQL(this) 

    println(rawSQL)
}
Note that this will not execute your SQL, it will only print it
e

Eric Thomas

03/30/2023, 3:59 PM
Thank you very much, that worked! Is it possible to do the same thing from an entity? ex:
object TestTable : UUIDTable(columnName = "id", name = "test_table") {
    val data = uuid("data")
}

class TestRecord(id: EntityID<UUID>) : UUIDEntity(id) {
    var data by TestTable.data
}

val rawSQL = transaction {
    TestRecord.findById(<id>).prepareSQL(this)
}

println("rawSQL: $rawSQL")
@Alexey Soshin
View count: 8