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
  • m

    maxmello

    07/25/2022, 3:51 PM
    I have a problem with my custom ColumnType which are GENERATED columns for Postgres. In this minimal example, while running
    SchemaUtils.drop(ExampleTable); SchemaUtils.createMissingTablesAndColumns(ExampleTable)
    , so recreating the table completely, I get the following log output:
    17:02:26.029 [DefaultDispatcher-worker-1 @coroutine#3] DEBUG Exposed - DROP TABLE IF EXISTS example
    17:02:26.066 [DefaultDispatcher-worker-1 @coroutine#3] INFO Exposed - Preparing create tables statements took 36ms
    17:02:26.073 [DefaultDispatcher-worker-1 @coroutine#3] DEBUG Exposed - CREATE TABLE IF NOT EXISTS example (id BIGSERIAL PRIMARY KEY, "name" VARCHAR(64) NOT NULL, "isNamedAlice" BOOLEAN GENERATED ALWAYS AS ( example."name" = 'Alice' ) STORED NOT NULL)
    17:02:26.084 [DefaultDispatcher-worker-1 @coroutine#3] INFO Exposed - Executing create tables statements took 17ms
    17:02:26.097 [DefaultDispatcher-worker-1 @coroutine#3] INFO Exposed - Extracting table columns took 13ms
    17:02:26.113 [DefaultDispatcher-worker-1 @coroutine#3] INFO Exposed - Extracting column constraints took 14ms
    17:02:26.113 [DefaultDispatcher-worker-1 @coroutine#3] INFO Exposed - Preparing alter table statements took 29ms
    17:02:26.124 [DefaultDispatcher-worker-1 @coroutine#3] DEBUG Exposed - ALTER TABLE example ALTER COLUMN "isNamedAlice" TYPE BOOLEAN GENERATED ALWAYS AS ( example."name" = 'Alice' ) STORED
    17:02:26.127 [DefaultDispatcher-worker-1 @coroutine#3] WARN Exposed - Transaction attempt #1 failed: org.postgresql.util.PSQLException: ERROR: syntax error at or near "GENERATED"
    As you can see, the table is originally created with the column “isNamedAlice” having NOT NULL, then immediately altered without that NOT NULL part. When looking into
    createMissingTablesAndColumns
    , there seems to be a ColumnDiff triggered between the ColumnMetadata and Column. I could not find out which of the 4 comparisons triggered the change detection, but when looking into
    org.jetbrains.exposed.sql.vendors.PostgreSQL modifyColumn
    , there only nullability and defaults are checked, and since both do not appear in the modify statement, I assume it is one of the other 2 (auto inc or case sensitive name). Please look at the snippet for reference, even though I would say that an ALTER COLUMN statement should never trigger in this case. In addition, the problem here is that GENERATED columns do not support ALTER COLUMN at all, only DROP/ADD column, resulting in the syntax error. There is currently no possibility to override modifyStatement from Column I think, but I guess the real problem remains that this modify statement is even executed with nothing actually modified. (Postgres 14.4, Exposed 0.38.2, Kotlin 1.6.21, also tested with Exposed 0.37.3, 0.36.2)
    • 1
    • 1
  • p

    phldavies

    07/26/2022, 11:06 AM
    Is there a nice way to extend an existing column type? For example, if I have a
    value class Id(id: String)
    I’d like to have a column
    Column<Id>
    that wraps a
    varchar(12)
    .
    r
    • 2
    • 3
  • w

    Wyatt Kennedy

    07/31/2022, 1:25 AM
    I'm having difficulty getting schema operations to work with a specified schema. I'm using postgres, I've already created a schema, but the createMissingTablesAndColumns fails with error "ERROR: no schema has been selected to create in". My attempt is below:
    fun generateSchema(config: Config) {
        val ds = PGSimpleDataSource()
        ds.serverNames = arrayOf(config.host)
        ds.databaseName = config.database
        ds.user = config.username
        ds.password = config.password
        ds.currentSchema = config.schema
    
        val actualDb = Database.connect(ds, databaseConfig = DatabaseConfig{
            defaultSchema = Schema(config.schema)
        })
        transaction(actualDb) {
            println(connection.schema)
            SchemaUtils.setSchema(Schema(config.schema))
            SchemaUtils.createMissingTablesAndColumns(*SCHEMA_LIST, withLogs = true)
        }
    }
    • 1
    • 3
  • o

    Ovsyannikov Alexey

    07/31/2022, 8:24 AM
    Hello :) have somebody tested jetbrains exposed 0.38.2 compatibility with kotlin 1.7.10/1.7.0? I am planning to update my tree of projects, but I am not pretty sure if everything will be ok or not
    a
    a
    • 3
    • 3
  • t

    tapac

    08/01/2022, 3:31 PM
    Hi there! Long time no see. I was in process of relocation from Russia due to JetBrains stopped to work there so I didn't have time to work on Exposed too much. But now I hope to spend more time on it. Lets start with Exposed 0.39.1 release with Kotlin 1.7.10 support and much more fixes and improvements. Please check change log for details,
    a
    s
    • 3
    • 3
  • g

    Gustav Elmgren

    08/03/2022, 3:01 PM
    Hi guys, I am trying to do something similar to this: https://kotlinlang.slack.com/archives/C0CG7E0A1/p1562480137054600 Has this changes? Because
    inList
    seems not to like the
    Expression<List<EntityId<>>>
    in my case, and the thread was from three years ago...
    • 1
    • 1
  • t

    tapac

    08/03/2022, 9:30 PM
    Maintenance release 0.39.2 with libs update and few improvements.
  • r

    Robert Kempton

    08/04/2022, 4:20 PM
    Has anyone figured out a good way to serialize/deserialize an Entity? I'm using a data class DTO as an intermediate for now, but there's soooooo much boiler plate...
    j
    m
    +2
    • 5
    • 9
  • p

    phldavies

    08/08/2022, 11:21 AM
    is
    ignoreAndGetId
    supposed to work differently for UUIDTable and IntTable?
    • 1
    • 2
  • f

    Filip Lastic

    08/08/2022, 1:31 PM
    [Sharing transactions between threads] Hello. I know that the documentation contains this message:
    you should not try to share a transaction between multiple threads as it will lead to undefined behaviour.
    , but we have one usecase where we need to share transactions between threads. We have GraphQL DataLoaders https://opensource.expediagroup.com/graphql-kotlin/docs/server/data-loader/. DataLoader can be executed inside another thread and we have to call database query inside it. We solved the issue by using nested transactions and using wrapper on our code:
    TransactionManager.manager.bindTransactionToThread(outerTx)
    return synchronized(outerTx) {
        transaction {
            TransactionManager.manager.bindTransactionToThread(this)
            statement()
        }
    }
    Do you think this this is a totally anti-pattern and we should do this in some other way or it is an acceptable solution?
  • g

    Gustav Elmgren

    08/09/2022, 1:59 PM
    Hi guys, I have some trouble with Kotlin, more then exposed maybe, so it might be the wrong channel. But lets say I have the following:
    Flights
        .join(...)
        .join(...)
    And then I have an optional
    join
    based on another parameter. One solution I guess is to use a var:
    var joins = Flights
        .join(...)
        .join(...)
    
    if (condition) { joins = joins.join(AnotherTable...) }
    Is there any feature in kotlin that make it possible to do the if in the assignment so I can keep it as a
    val
    ? (or something like
    adjustWhere
    in Exposed)
    Flights
        .join(...)
        .join(...)
        .someMagicKotlinMethod {
           if (condition) ...
        }
    p
    k
    • 3
    • 7
  • m

    Muhammad Talha

    08/17/2022, 5:00 AM
    Hey all - beginner here: What’s the best way to decouple the DAO API from my app? It looks like the DAO API is both an entity and a DAO so I was wondering what the best way to go about this was. I could just resort to using the DSL API and have my own DAO object and Entity, but was hoping to avoid the boilerplate of mapping table properties to that entity. Thanks!
    p
    • 2
    • 4
  • p

    ptmt

    08/22/2022, 9:44 AM
    What's the best way to understand if this executed statement was actually executed or just hit the entity cache? (If I understood correctly how it works)
    override fun afterExecution(
        transaction: Transaction,
        contexts: List<StatementContext>,
        executedStatement: PreparedStatementApi,
    ) {
        
    }
  • h

    hhariri

    08/23/2022, 12:51 PM
    Folks, I have a question if you don’t mind - what’s the main reason(s) you’ve chosen Exposed over other solutions?
    b
    e
    +8
    • 11
    • 10
  • g

    Gustav Elmgren

    08/26/2022, 8:30 AM
    Hi guys, I had a method which calculated distance between two points, like so:
    fun distanceInKm(lat1: Column<Double>, long1: Column<Double>, lat2: Column<Double>, long2: Column<Double>) =
        Expression.build {
            ACos(
                Sin(
                    (doubleLiteral(PI) * lat1 / doubleLiteral(180.0))
                ) *
                    Sin(doubleLiteral(PI) * lat2 / doubleLiteral(180.0))
                    +
                    Cos(doubleLiteral(PI) * lat1 / doubleLiteral(180.0)) *
                    Cos(doubleLiteral(PI) * lat2 / doubleLiteral(180.0)) *
                    Cos(doubleLiteral(PI) * (long1 - long2) / doubleLiteral(180.0))
            ).times(
                doubleLiteral(180.0) / doubleLiteral(PI) * doubleLiteral(60.0) * doubleLiteral(1.1515) * doubleLiteral(
                    1.609344
                )
            )
        }
    But I just realized that two of the columns are nullable (
    lat2
    ,
    long2
    ), which breaks the method. Is there anything like
    !!
    in exposed? Given I know the values are not null because of my
    where
    .
    • 1
    • 3
  • z

    zt

    08/30/2022, 4:04 AM
    How would I set a default value for the markovConfig column on a Guild?
    object Guilds : IntIdTable() {
        val markovConfig = reference("markov_config", MarkovConfigs)
    }
    
    class Guild(id: EntityID<Int>) : IntEntity(id) {
        companion object : IntEntityClass<Guild>(Guilds)
    
        var markovConfig by MarkovConfig referencedOn Guilds.markovConfig
    }
    
    object MarkovConfigs : IntIdTable() {
        val frequency = float("frequency")
        val handleMention = bool("handle_mention").default(true)
    }
    
    class MarkovConfig(id: EntityID<Int>) : IntEntity(id) {
        companion object : IntEntityClass<MarkovConfig>(MarkovConfigs)
    
        var frequency by MarkovConfigs.frequency
        var handleMention by MarkovConfigs.handleMention
    }
  • g

    Gustav Elmgren

    08/30/2022, 3:09 PM
    Hi guys, I have some trouble understanding something, it is related to the
    timestamp
    type in exposed. I have a postgres db with with a table that has a
    timestamp
    column. And the
    timestamp
    in exposed is of
    JavaInstantColumnType
    . Both instant and the column type in postgres does not have a concept of timezones. So why is the system timezone applied when I fetch the column via exposed? Is this possible to prevent?
    • 1
    • 2
  • b

    Bartłomiej Kozak

    09/02/2022, 5:51 PM
    Hi. Is there any difference between
    suspend fun <T> dbQuery(block: suspend () -> T): T = newSuspendedTransaction(<http://Dispatchers.IO|Dispatchers.IO>) { block() }
    
    override suspend fun isEmailTaken(email: String): Boolean = dbQuery {
            UserEntity.find {
                UsersTable.email eq email
            }.firstOrNull()
        } == null
    and
    override suspend fun isEmailTaken(email: String): Boolean = dbQuery {
            UserEntity.find {
                UsersTable.email eq email
            }.firstOrNull() == null
        }
    ? Should I check if the value exists in the another way?
    t
    • 2
    • 1
  • h

    Hachemi Hamadi

    09/03/2022, 11:20 AM
    SOLVED Hi, I am facing an issue when trying to compile a JavaFX project with Exposed. When using DSL APIs everything works well. But when I try to create entity for my rows and then call it like below:
    object OperatorsTable : IdTable<String>("operators") {
        override val id: Column<EntityID<String>> = varchar(name = "id", length = 14).entityId().uniqueIndex()
        val name = varchar("name", length = 50)
        ......
    }
    
    class OperatorEntity(id: EntityID<String>) : StringEntity(id) {
        companion object : StringEntityClass<OperatorEntity>(OperatorsTable)
        var name by OperatorsTable.name
        ....
    }
    
    // Get all
    val usersList = transaction {
        OperatorEntity.all().toList()
    }
    I get this error:
    java.lang.IllegalStateException: Resource not found in classpath: kotlin/kotlin.kotlin_builtins
    Exposed Version: 0.39.2 PostgresDriver: 42.5.0 Kotlin: 1.7.10 Any idea why this is happening ?
    • 1
    • 1
  • p

    Pratik Tandel

    09/13/2022, 2:08 AM
    I couldn't find documentation for this but how does exposed handle cancellations and interruptions. Lets say I run it from some thread that gets interrupted. Does exposed cancel the jdbc transaction in that case?
  • s

    Stuart Baker

    09/15/2022, 6:17 PM
    Hey everyone, I was thinking about writing a basic script that takes in a yaml spec (similar to openapi in format), and generates DSL tables + basic CRUDL functions (maybe routes for ktor). I’ve find when creating new tables a lot of the work is very repetitive and automate-able. Before doing so I wanted to check to see if anybody has done this already?
    e
    • 2
    • 1
  • t

    TheOnlyTails

    09/17/2022, 6:13 PM
    hi, is it just me or does exposed not work with jetpack compose on android? i keep getting this really weird error:
    org.postgresql.util.PSQLException: Something unusual has occurred to cause the driver to fail. Please report this exception.
    here is the full log: https://gist.github.com/TheOnlyTails/a5e901beef65f023973c8b22136a8823
    h
    • 2
    • 1
  • s

    Sergei

    09/19/2022, 12:06 PM
    Hi, have been playing with Exposed and the DAO part recently, and found out that unfortunately DAOs don’t support composite primary keys yet. Is there any information if this feature is planned to be implemented and if yes - when?
  • z

    zt

    10/03/2022, 10:56 PM
    transaction {
        Filter.new {
            guild = Guild.findById(guildId)!!
            pattern = arguments.filter.toString()
            action = FilterAction.REPLY
            response = arguments.content
        }
    }
    Is there some simpler way of doing this? like instead I would fetch the Guild database object and then insert into its filters column
  • s

    Suser

    10/04/2022, 6:59 AM
    How would one go about getting real time updates via exposed? it seems like you can't really subscribe to anything do people just poll? (new to backend)
    e
    t
    • 3
    • 4
  • a

    Adam Cooper

    10/04/2022, 7:36 PM
    It seems that most people use Flyway for migrations with Exposed. I also notice that there are plans to port Exposed to Native and JS. Since Flyway is a Java-only tool, migrations on these platforms would become a great challenge. Is there any plan to add a native (as in: part of the library) migration framework to Exposed? It's not on the roadmap, but it seems like something that would bring it up-to-par with popular ORMs from other languages.
  • t

    tapac

    10/05/2022, 1:45 PM
    Hi all, new release of Exposed 0.40.1 is available now. Please check the list of new features and bug fixes here.
    p
    • 2
    • 1
  • b

    Berkay Özkan

    10/06/2022, 1:12 PM
    Hi, I have an entities for example from exposed wiki
    object Users: IntIdTable() {
        val name = varchar("name", 50)
    }
    
    class User(id: EntityID<Int>): IntEntity(id) {
        companion object : IntEntityClass<User>(Users)
        var name by Users.name
    }
    
    object UserRatings: IntIdTable() {
        val value = long("value")
        val user = reference("user", Users)
    }
    
    class UserRating(id: EntityID<Int>): IntEntity(id) {
        companion object : IntEntityClass<UserRating>(UserRatings)
        var value by UserRatings.value
        var user by User referencedOn UserRatings.user
    }
    When i want to create new UserRating i get id of user, and value (5 star etc)
    val movie = UserRating.new {
      value = 5
      user = ? // This expects an User object
    }
    How can I use only id when creating UserRating? Or do i have to get User from db with selectById? (Isn’t it unneccesarry get operation?)
  • j

    Jackie Whittle

    10/07/2022, 2:56 PM
    Question from a exposed newbie After searching the exposed documentation and google if have found everything from you cant serialize an exposed model to creating a data class to do the conversion, Can someone point me to the best way to serialize an exposed table to return json with Ktor.
    e
    • 2
    • 2
  • g

    Gustav Elmgren

    10/18/2022, 2:06 PM
    Hi everyone, I'm trying to eager load some relations using
    .with(Entity::relation
    , but when said relation is accessed, outside of the transaction it was fetched from, I get
    Can't init value outside the transaction
    . My understanding was that using
    With
    would load all relations eagerly, is that wrong?
    l
    • 2
    • 3
Powered by Linen
Title
g

Gustav Elmgren

10/18/2022, 2:06 PM
Hi everyone, I'm trying to eager load some relations using
.with(Entity::relation
, but when said relation is accessed, outside of the transaction it was fetched from, I get
Can't init value outside the transaction
. My understanding was that using
With
would load all relations eagerly, is that wrong?
l

Leonid Yavorskyi

10/18/2022, 7:26 PM
You can’t load eagerly outside of transaction
NOTE: References that are eagerly loaded are stored inside the Transaction Cache, this means that they are not available in other transactions and thus must be loaded and referenced inside the same transaction.
https://github.com/JetBrains/Exposed/wiki/DAO#eager-loading
g

Gustav Elmgren

10/18/2022, 7:27 PM
Oh damn... I missed that. Thanks!
View count: 30