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

Kotlin Column Default #25

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions squash-core/src/org/jetbrains/squash/definition/ColumnProperty.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ fun <V> ReferenceColumn<V>.nullable(): ReferenceColumn<V?> = addProperty(Nullabl
*/
fun <V, C : ColumnDefinition<V>> C.default(value: V): C = addProperty(DefaultValueProperty(value))

fun <V, C : ColumnDefinition<V>> C.default(generate: () -> V?):C = addProperty(DefaultValueProperty(null, generate))

object AutoIncrementProperty : ColumnProperty {
override fun toString(): String = "++"
}
Expand All @@ -36,8 +38,20 @@ object NullableProperty : ColumnProperty {
override fun toString(): String = "?"
}

class DefaultValueProperty<out V>(val value: V) : ColumnProperty {
override fun toString(): String = "= $value"
class DefaultValueProperty<out V>(defaultValue: V?, private val generate:(() -> V)? = null) : ColumnProperty {

val value:V? = defaultValue
get():V? {
return if (generate != null) {
val result = generate.invoke()
println("Generated Value 1: $result")
result ?: field
} else {
field
}
}

override fun toString(): String = "= $value"
}


13 changes: 11 additions & 2 deletions squash-core/src/org/jetbrains/squash/statements/Insert.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,22 @@ open class InsertValuesStatement<T : Table, R>(val table: T) : Statement<R> {
val values: MutableMap<Column<*>, Any?> = LinkedHashMap()

operator fun <V, S : V> set(column: Column<@Exact V>, value: S?) {
// Error if the column is being set more than once
if (values.containsKey(column)) {
error("$column is already initialized")
}
if (column.properties.all { it !is NullableProperty } && value == null) {

val finalValue = value ?: if (column.hasProperty<DefaultValueProperty<S>>())
column.propertyOrNull<DefaultValueProperty<S>>()!!.value
else
null

// Error if the column is not nullable and it is getting set to null
if (column.properties.none { it is NullableProperty } && finalValue == null) {
error("Trying to set null to not nullable column $column")
}
values[column] = value

values[column] = finalValue
}

operator fun <V> get(column: Column<V>): Any? = values[column]
Expand Down