Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to handle exception on unique constrain? #63

Closed
chenzhendong opened this issue Nov 8, 2016 · 1 comment
Closed

How to handle exception on unique constrain? #63

chenzhendong opened this issue Nov 8, 2016 · 1 comment

Comments

@chenzhendong
Copy link

object PropName : Table("tblProperty") {
val id = integer("id").autoIncrement().primaryKey()
val name = varchar("name", 50).uniqueIndex()
}
propNameId = PropName.insert {
it[name] = aname
} get PropName.id

I want a logic
if name exists
return id
else
do insert and return id
is there any simple way to write code?

@JonLatane
Copy link
Contributor

JonLatane commented Nov 11, 2016

Use INSERT IGNORE.

fun getPropertyId(name: String) : Int? = PropName.select {
  PropName.name eq "blah"
}.firstOrNull()?[PropName.id]


fun getOrCreatePropertyId(name: String) : Int {
  PropName.insertIgnore { it[name] = name }
  return getPropertyId(name)!!
}

(This probably won't compile, but should get you started.)

@Tapac Tapac closed this as completed Dec 7, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants