https://kotlinlang.org logo
Docs
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
  • s

    Sandeep Chandra

    04/06/2021, 9:28 AM
    Is there any tool to generate structures for existing database?
    b
    l
    • 3
    • 4
  • e

    Endre Deak

    04/12/2021, 8:12 PM
    seems there’s a breaking change in version
    0.30.1
    -
    Query.prepareSql(queryBuilder: QueryBuilder)
    is now internal. What’s the right way to print out the Query SQL then?
    t
    • 2
    • 4
  • l

    Luca Piccinelli

    04/16/2021, 12:11 PM
    Hello everyone. Do anyone knows if exposed is suitable for production?
    e
    e
    • 3
    • 2
  • l

    Luca Piccinelli

    04/16/2021, 3:14 PM
    Thank you for your answer 😃
    t
    • 2
    • 3
  • c

    CLOVIS

    04/17/2021, 8:27 AM
    Hi, I found a weird behavior: I've got my table defined like this:
    object Profiles : IntIdTable() {
      val email = varchar("email", 50).uniqueIndex() // important!
      val name = varchar("name", 50)
    }
    Looking at the logs, it seems that the table is created correctly by Exposed:
    DEBUG Exposed - CREATE TABLE IF NOT EXISTS Profiles (id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(50) NOT NULL, name VARCHAR(50) NOT NULL)
    DEBUG Exposed - ALTER TABLE Profiles ADD CONSTRAINT Profiles_email_unique UNIQUE (email)
    Because of the unique index, I would expect
    insert
    requests with an email already present in the database, to fail:
    Profiles.insert { profile ->
      profile[this.email] = email
      profile[this.name] = name
    }
    In the above example, I would expect an
    insert
    to be fail if the email is already used by another profile. Nothing seems weird in debug either;
    DEBUG Exposed - INSERT INTO Profiles (email, name) VALUES ('some random <http://email.fr|email.fr>', 'my full name')
    However, when running this code multiple times, instead of failing on the
    insert
    , it simply replaces the previous entry that had the same email. In case it's relevant, I'm using MariaDB. For obvious reasons, I don't want users of the software to be able to replace other accounts. I'm not sure if the current behavior is 'normal' or 'bugged', so I'm asking here whether: 1. Is it normal behavior, or should I submit a bug report? 2. If this is normal behavior, what should I change in my code so the
    insert
    fails (with an exception or something else)?
    s
    • 2
    • 2
  • m

    Miroslav Sobotka

    04/19/2021, 7:34 AM
    Hello, I have already searched here, but I did not find an answer. How can I build a sql via DSL or Dao that looks like this:
    select count(ID) from employer
    The ID column is primary key, so uniq and has no nulls.
    Employer.slice(Employer.Id).count()
    produces
    select count(*) from employer
    Thanks!
    t
    a
    • 3
    • 4
  • d

    dave08

    04/19/2021, 5:17 PM
    Is R2DBC coming soon? Also, would there be a way to separate the entity definitions that are only for DDL? I'm sure alot of us use tools like flyway for that and exposed only for working with the existing structure... and I'm never sure what is the minimum I need for no DDL use @tapac ...
    t
    • 2
    • 3
  • j

    John Pena

    04/19/2021, 8:36 PM
    i get errors with the following error message when i try to query using an enum value:
    Transaction attempt #0 failed: org.postgresql.util.PSQLException: ERROR: operator does not exist: "MyEnumColumn" = character varying\n  Hint: No operator matches the given name and argument types. You might need to add explicit type casts
    e
    • 2
    • 20
  • d

    Dominick

    04/23/2021, 3:33 PM
    I've practically copy and pasted this from the docs, but I get an error in Intellij. I will edit to provide, one moment (see thread)
    UserTable.update({ UserTable.userId eq userId }) {
                        it[UserTable.hashedPassword] = hash(randomAlphanumerical(8))
                    }
    ✅ 1
    • 1
    • 2
  • l

    Luca Piccinelli

    04/24/2021, 2:00 PM
    @tapac I have this code
    object BuddyTable: IdTable<Int>("toh.buddy"){
        override val id = integer("id").autoIncrement("toh.buddy_seq_id").entityId()
        val name = varchar("name", 50)
        val hero = reference("hero_id", HeroTable)
    }
    
    class BuddyDao(id: EntityID<Int>) : IntEntity(id) {
        companion object : IntEntityClass<BuddyDao>(BuddyTable)
    
        var name by BuddyTable.name
        var hero by HeroDao referencedOn BuddyTable.hero
    }
    
    override fun save(entity: Buddy): Int = transaction {
            BuddyTable.insert {
                it[name] = entity.name
                it[hero] = entity.hero.id
            }[BuddyTable.id].value
    }
    In postgres it looks like it is not using the sequence to generate the new id (also if i don't override the id field) Prefixing or not with the schema "toh" doesn't change. The error is
    Detail: Key (id)=(3) already exists.. Statement(s): INSERT INTO toh.buddy (hero_id, "name") VALUES (?, ?)
    
    org.jetbrains.exposed.exceptions.ExposedSQLException: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "buddy_pkey"
      Detail: Key (id)=(3) already exists.
    It does 3 transaction attempts with ids 1, 2 and 3
    t
    • 2
    • 4
  • t

    tapac

    04/25/2021, 7:44 PM
    Expose 0.31.1 released with TIME column support (java-time only), inList on Pairs and Triples, few fixes, and performance improvement. Check change log for details.
    👏 5
    b
    j
    • 3
    • 4
  • a

    Ali Olfat

    04/26/2021, 4:39 AM
    hey folks, is there a way to know if my row was inserted or not with
    insertIgnore
    on a non IdTable? I'm currently querying for it right afterwards but was wondering if there is a cleaner way
    t
    • 2
    • 1
  • l

    Luca Sas

    04/27/2021, 6:48 PM
    Hi, I am on ktor 1.5.2 and I am having issues with SchemaUtils.create. I have 3 tables, and the third has a reference to the first one. When it gets to creating the third table it concludes that the first one doesnt exist and tries to create it again which causes an error "relation "users_username_unique" already exists". I debugged and stepped thru the code and found that the problem is in VendorDialect.tableExists function.
    override fun tableExists(table: Table): Boolean {
            val tableScheme = table.tableName.substringBefore('.', "").takeIf { it.isNotEmpty() }
            val scheme = tableScheme?.inProperCase() ?: TransactionManager.current().connection.metadata { currentScheme }
            val allTables = getAllTableNamesCache().getValue(scheme)
            return allTables.any {
                when {
                    tableScheme != null -> it == table.nameInDatabaseCase()
                    scheme.isEmpty() -> it == table.nameInDatabaseCase()
                    else -> it == "$scheme.${table.tableNameWithoutScheme}".inProperCase()
                }
            }
        }
    What happens here by looking at the debugger is that
    alltables
    is
    [ "public.tablename", "public.someothertablename" ]
    but
    table.name
    misses the schema name and I am not sure why. The code is fairly straightforward and I used
    SchemaUtils.create
    successfully in the past.
    t
    • 2
    • 1
  • d

    Dominick

    04/28/2021, 3:24 AM
    Do I need to call Database.connect(dataSource) every time I create a transaction? I'm receiving errors and I'm kind of confused because I do call it after I create the datasource
    d
    • 2
    • 2
  • d

    Dominick

    04/28/2021, 4:02 AM
    It's possible that my database doesn't connect. I just went into my database and it doesn't seem that it created anything:
    val dataSource = HikariDataSource().apply {
            maximumPoolSize = 20
            driverClassName = "com.mysql.jdbc.Driver"
            jdbcUrl = File("jdbc_url.txt").readText()
            isAutoCommit = false
        }
    
        Database.Companion.connect(dataSource)
    
        transaction {
            SchemaUtils.create(MediaPropertiesTable)
            SchemaUtils.create(MediaContentTable)
            SchemaUtils.create(UserAPIKeysTable)
            SchemaUtils.create(UserTable)
        }
    The file jdbc_url.txt does exist and has a connection url generated from pterodactyl UPDATE: Tried removing pterodactyl from the equation and still doesnt work. It gets past the create code and all, nothing gets logged even after adding
    addLogger(StdOutSqlLogger)
    and the tables arent in the db.
    ✅ 1
    b
    t
    • 3
    • 5
  • j

    Joost Klitsie

    04/29/2021, 7:35 AM
    Hi all! I wish to create some custom column types, mainly to wrap inline classes for UUID's. I have multiple classes that wrap a UUID, and I was wondering that if there is any guide to help me through it? I could copy paste and adjust the UUIDColumnType, but I was wondering, is it somehow possible to wrap something around it?
    e
    • 2
    • 9
  • c

    christophsturm

    04/30/2021, 1:42 PM
    does expose always use threadLocals? i thought that if I pass around a database and always specify the database like
    transaction(db) {..}
    it will avoid threadlocals, but it seems that all exposed calls inside the transaction still get their transaction from a threadlocal. so it only works if the thread stays the same, and for example it wont work if i have callbacks (or coroutines) that potentielly run in different threads.
    e
    b
    • 3
    • 3
  • e

    Emil Kantis

    05/02/2021, 5:33 PM
    I'm getting some odd error regarding with DAOs when writing tests
    <http://dao.Companies.org|dao.Companies.org>_id is not in record set
    . All tables are created in the same transaction as the test then everything is rolled back. I've tried using both H2 and SQLite, getting same error with both.. Not sure where to start looking. Most search hits seems to be related to renaming the id column, but this is a FK to another entity
    m
    • 2
    • 3
  • a

    Ali Albaali

    05/13/2021, 5:43 PM
    Is there a way to return a
    Flow
    from a query?
    j
    • 2
    • 9
  • s

    spand

    05/18/2021, 8:03 AM
    Am I missing a way to put a Query in the slice ? ie.
    INSERT INTO Tbl (parentId, number)
    VALUES (42,
            COALESCE((SELECT MAX(aTbl.number) FROM Tbl as aTbl WHERE aTbl.parentId = 42) + 1, 1)
            );
    I kind of expected a way to turn a query into an Expression<Int>.
    • 1
    • 1
  • j

    Jamy

    05/25/2021, 6:16 AM
    Hello ! Is there a way to avoid duplicate row when insert data in many to many table with exposed ?
    s
    • 2
    • 1
  • r

    Renaud

    05/28/2021, 2:30 PM
    I have a Publication object and i’d like to insert a batch of them. Two options: 1. Insert only via the Entity
    for loop
      Publication.new { ... }
    2. Insert via entity table
    Publication.table.batchInsert
    1? 2? I’m not sure
    s
    b
    • 3
    • 4
  • e

    ESchouten

    06/07/2021, 4:04 PM
    Is there any way I can set the childs' ReferenceOption.Cascade from the parent entity? The child table is referenced from multiple tables, and I want to avoid optionally referencing each of the tables at the child level Example:
    object Person : UUIDTable() {
        val name = varchar("name", 255)
        val address = reference("address", Address)
    }
    
    object Company : UUIDTable() {
        val name = varchar("name", 255)
        val address = reference("address", Address)
    }
    
    object Address : UUIDTable() {
        val number = varchar("number", 255)
        val street = varchar("street", 255)
        val city = varchar("city", 255)
        val zipcode = varchar("zipcode", 255)
        val country = varchar("country", 255)
    }
    t
    • 2
    • 5
  • e

    Emil Kantis

    06/07/2021, 8:36 PM
    I'm kinda new with delegates.. I'd like to create one to help me store json in a varchar column.. My gut feeling tells me I'm overcomplicating things here.. Any feedback on better approaches? 🙏
    // Entity
    class Client(id: EntityID<Int>) : IntEntity(id) {
       companion object : IntEntityClass<Client>(Clients)
       // Some code omitted
       var tags2: List<String> by jsonStore(Clients.tags)
    }
    
    // Delegate provider
    inline fun <reified S, T : Comparable<T>> Entity<T>.jsonStore(column: Column<String>) = JsonStore<T, S>(
       serializer(),
       column,
       { column.lookup() },
       { thisRef, property, value -> column.setValue(thisRef, property, value) }
    )
    
    // Delegate
    class JsonStore<T : Comparable<T>, S>(
       val serializer: KSerializer<S>,
       val column: Column<String>,
       val lookup: (Column<String>) -> String,
       val write: (Entity<T>, KProperty<*>, String) -> Unit
    ) {
       
       operator fun getValue(thisRef: Any?, property: KProperty<*>): S = 
          json.decodeFromString(serializer, lookup(column))
       
       operator fun setValue(thisRef: Entity<T>, property: KProperty<*>, value: S) = 
          write(thisRef, property, json.encodeToString(serializer, value))
    }
    r
    • 2
    • 7
  • j

    Jeff

    06/10/2021, 9:17 AM
    I want to use an alias for the order by clause in Exposed Kotlin like so:
    6371 * ACOS(COS(RADIANS(:latitude)) * COS(RADIANS(`lat`)) * COS(RADIANS(:longitude) - RADIANS(`lng`)) + SIN(RADIANS(:latitude)) * SIN(RADIANS(`lat`))) AS `distance`
    Anyone with an idea on how to implement this?
    s
    e
    t
    • 4
    • 14
  • m

    Matias Rozenblum

    06/14/2021, 2:34 PM
    Hi everyone! I’m having an issue using Exposed, in my app i’m doing several inserts to a MySQL DB with Exposed, and sometimes instead of inserting the right data, it inserts zeroes on every column. This does not happen on every insert, for testing purposes I made two identical inserts, with the same hardcoded data, and even then one was saved with zeroes on every column while the other was correctly saved. I managed to turn on the Exposed debug logs and saw that the Insert query is formed correctly, even tried copying and executing it by hand on MySQL Workbench and it worked, but when I try via my app, it sometimes stores zeroes, does this happened to anyone before or know what could be de problem? Thanks!
    t
    • 2
    • 3
  • t

    tapac

    06/14/2021, 6:10 PM
    Hello everyone, I'm glad to announce that the
    exposed-gralde-plugin
    is here with a very small but usefult gradle task which allows to generate tables definitions by existing scheme. https://plugins.gradle.org/plugin/com.jetbrains.exposed.gradle.plugin The main idea is allow easily migrate your large (or not so large) existing projects to Exposed. Please check a documentation on github and share your ideas on things that can be improved/added to a gradle plugin. For now I think that it can be useful to generate/validate schemas or prepare migration scripts (like ShemaUtils do). What do you think? The on of the next steps is to have intellij-idea plugin to have same things in the IDE, so share your thoughts about that too:) P.S. There can be bugs for sure:)
    :nice: 11
    👍 4
    b
    s
    +2
    • 5
    • 10
  • t

    Tim McCormack

    06/20/2021, 10:54 PM
    If I connect to a SQLite DB in Exposed and use the same
    Database
    instance in separate transactions in two separate threads... I would expect to see uncommitted reads and similar. But I can't seem to reproduce that with a test. Does Exposed do something to ensure isolation?
    t
    • 2
    • 5
  • d

    dave08

    06/28/2021, 3:11 PM
    The
    generateExposedTask
    has been stuck for more than half-an-hour without crashing nor telling me what's wrong... how can I debug this?
    b
    t
    • 3
    • 12
  • r

    rcd27

    07/02/2021, 7:16 AM
    Greetings, I'm new to databases in general, but I have a pet-project with whole-Kotlin infrastructure and want to implement
    exposed
    . The task is: store ~2.5K items in one table with ability to full-text-search against the item
    name
    field. Which database supported by
    Exposed
    is my choice of best performance?
    c
    • 2
    • 1
Powered by Linen
Title
r

rcd27

07/02/2021, 7:16 AM
Greetings, I'm new to databases in general, but I have a pet-project with whole-Kotlin infrastructure and want to implement
exposed
. The task is: store ~2.5K items in one table with ability to full-text-search against the item
name
field. Which database supported by
Exposed
is my choice of best performance?
c

crummy

07/02/2021, 8:04 AM
With so few items probably any would do fine
👍 3
View count: 5