-
Notifications
You must be signed in to change notification settings - Fork 666
/
ColumnType.kt
883 lines (738 loc) · 30.1 KB
/
ColumnType.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
package org.jetbrains.exposed.sql
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.EntityIDFunctionProvider
import org.jetbrains.exposed.dao.id.IdTable
import org.jetbrains.exposed.sql.statements.DefaultValueMarker
import org.jetbrains.exposed.sql.statements.api.ExposedBlob
import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi
import org.jetbrains.exposed.sql.vendors.MariaDBDialect
import org.jetbrains.exposed.sql.vendors.currentDialect
import java.io.InputStream
import java.lang.IllegalArgumentException
import java.math.BigDecimal
import java.math.MathContext
import java.math.RoundingMode
import java.nio.ByteBuffer
import java.sql.Blob
import java.sql.Clob
import java.sql.ResultSet
import java.util.*
import kotlin.reflect.KClass
/**
* Interface common to all column types.
*/
interface IColumnType {
/** Returns `true` if the column type is nullable, `false` otherwise. */
var nullable: Boolean
/** Returns the SQL type of this column. */
fun sqlType(): String
/**
* Converts the specified [value] (from the database) to an object of the appropriated type, for this column type.
* Default implementation returns the same instance.
*/
fun valueFromDB(value: Any): Any = value
/** Returns an object compatible with the database, from the specified [value], for this column type. */
fun valueToDB(value: Any?): Any? = value?.let(::notNullValueToDB)
/** Returns an object compatible with the database, from the specified **non-null** [value], for this column type. */
fun notNullValueToDB(value: Any): Any = value
/**
* Returns the SQL representation of the specified [value], for this column type.
* If the value is `null` and the column is not nullable, an exception will be thrown.
*/
fun valueToString(value: Any?): String = when (value) {
null -> {
check(nullable) { "NULL in non-nullable column" }
"NULL"
}
DefaultValueMarker -> "DEFAULT"
is Iterable<*> -> value.joinToString(",", transform = ::valueToString)
else -> nonNullValueToString(value)
}
/** Returns the SQL representation of the specified **non-null** [value], for this column type. */
fun nonNullValueToString(value: Any): String = notNullValueToDB(value).toString()
/** Returns the object at the specified [index] in the [rs]. */
fun readObject(rs: ResultSet, index: Int): Any? = rs.getObject(index)
/** Sets the [value] at the specified [index] into the [stmt]. */
fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) {
if (value == null || value is Op.NULL) {
stmt.setNull(index, this)
} else {
stmt[index] = value
}
}
/**
* Function checks that provided value is suites the column type and throws [IllegalArgumentException] otherwise.
* [value] can be of any type (including [Expression])
* */
@Throws(IllegalArgumentException::class)
fun validateValueBeforeUpdate(value: Any?) {}
}
/**
* Standard column type.
*/
abstract class ColumnType(override var nullable: Boolean = false) : IColumnType {
override fun toString(): String = sqlType()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ColumnType
if (nullable != other.nullable) return false
return true
}
override fun hashCode(): Int = 31 * javaClass.hashCode() + nullable.hashCode()
}
/**
* Auto-increment column type.
*/
class AutoIncColumnType(
/** Returns the base column type of this auto-increment column. */
val delegate: ColumnType,
private val _autoincSeq: String?,
private val fallbackSeqName: String
) : IColumnType by delegate {
private val nextValValue = run {
val sequence = Sequence(_autoincSeq ?: fallbackSeqName)
if (delegate is IntegerColumnType) sequence.nextIntVal() else sequence.nextLongVal()
}
/** Returns the name of the sequence used to generate new values for this auto-increment column. */
val autoincSeq: String?
get() = _autoincSeq.takeIf { currentDialect.supportsCreateSequence } ?: fallbackSeqName.takeIf { currentDialect.needsSequenceToAutoInc }
val nextValExpression: NextVal<*>? get() = nextValValue.takeIf { autoincSeq != null }
private fun resolveAutoIncType(columnType: IColumnType): String = when {
columnType is EntityIDColumnType<*> -> resolveAutoIncType(columnType.idColumn.columnType)
columnType is IntegerColumnType && autoincSeq != null -> currentDialect.dataTypeProvider.integerType()
columnType is IntegerColumnType -> currentDialect.dataTypeProvider.integerAutoincType()
columnType is LongColumnType && autoincSeq != null -> currentDialect.dataTypeProvider.longType()
columnType is LongColumnType -> currentDialect.dataTypeProvider.longAutoincType()
else -> guessAutoIncTypeBy(columnType.sqlType())
} ?: error("Unsupported type $delegate for auto-increment")
private fun guessAutoIncTypeBy(sqlType: String): String? = when (sqlType) {
currentDialect.dataTypeProvider.longType() -> currentDialect.dataTypeProvider.longAutoincType()
currentDialect.dataTypeProvider.integerType() -> currentDialect.dataTypeProvider.integerAutoincType()
else -> null
}
override fun sqlType(): String = resolveAutoIncType(delegate)
override fun equals(other: Any?): Boolean {
return when {
other == null -> false
this === other -> true
this::class != other::class -> false
other !is AutoIncColumnType -> false
delegate != other.delegate -> false
_autoincSeq != other._autoincSeq -> false
fallbackSeqName != other.fallbackSeqName -> false
else -> true
}
}
override fun hashCode(): Int {
var result = delegate.hashCode()
result = 31 * result + (_autoincSeq?.hashCode() ?: 0)
result = 31 * result + fallbackSeqName.hashCode()
return result
}
}
/** Returns `true` if this is an auto-increment column, `false` otherwise. */
val IColumnType.isAutoInc: Boolean get() = this is AutoIncColumnType || (this is EntityIDColumnType<*> && idColumn.columnType.isAutoInc)
/** Returns the name of the auto-increment sequence of this column. */
val Column<*>.autoIncColumnType: AutoIncColumnType?
get() = (columnType as? AutoIncColumnType) ?: (columnType as? EntityIDColumnType<*>)?.idColumn?.columnType as? AutoIncColumnType
@Deprecated("Will be removed in upcoming releases. Please use [autoIncColumnType.autoincSeq] instead", ReplaceWith("this.autoIncColumnType.autoincSeq"), DeprecationLevel.ERROR)
val Column<*>.autoIncSeqName: String?
get() = autoIncColumnType?.autoincSeq
internal fun IColumnType.rawSqlType(): IColumnType =
if (this is AutoIncColumnType) this.delegate else if (this is EntityIDColumnType<*> && idColumn.columnType is AutoIncColumnType) this.idColumn.columnType.delegate else this
class EntityIDColumnType<T : Comparable<T>>(val idColumn: Column<T>) : ColumnType() {
init {
require(idColumn.table is IdTable<*>) { "EntityId supported only for IdTables" }
}
override fun sqlType(): String = idColumn.columnType.sqlType()
override fun notNullValueToDB(value: Any): Any = idColumn.columnType.notNullValueToDB(
when (value) {
is EntityID<*> -> value.value
else -> value
}
)
override fun nonNullValueToString(value: Any): String = idColumn.columnType.nonNullValueToString(
when (value) {
is EntityID<*> -> value.value
else -> value
}
)
@Suppress("UNCHECKED_CAST")
override fun valueFromDB(value: Any): EntityID<T> = EntityIDFunctionProvider.createEntityID(
when (value) {
is EntityID<*> -> value.value as T
else -> idColumn.columnType.valueFromDB(value) as T
},
idColumn.table as IdTable<T>
)
override fun readObject(rs: ResultSet, index: Int): Any? = idColumn.columnType.readObject(rs, index)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as EntityIDColumnType<*>
if (idColumn != other.idColumn) return false
return true
}
override fun hashCode(): Int = 31 * super.hashCode() + idColumn.hashCode()
}
// Numeric columns
/**
* Numeric column for storing 1-byte integers.
*/
class ByteColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.byteType()
override fun valueFromDB(value: Any): Byte = when (value) {
is Byte -> value
is Number -> value.toByte()
is String -> value.toByte()
else -> error("Unexpected value of type Byte: $value of ${value::class.qualifiedName}")
}
}
/**
* Numeric column for storing unsigned 1-byte integers.
*/
@ExperimentalUnsignedTypes
class UByteColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.ubyteType()
override fun valueFromDB(value: Any): UByte {
return when (value) {
is UByte -> value
is Byte -> value.takeIf { it >= 0 }?.toUByte()
is Number -> value.toByte().takeIf { it >= 0 }?.toUByte()
is String -> value.toUByte()
else -> error("Unexpected value of type Byte: $value of ${value::class.qualifiedName}")
} ?: error("negative value but type is UByte: $value")
}
override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) {
val v = if (value is UByte) value.toByte() else value
super.setParameter(stmt, index, v)
}
override fun notNullValueToDB(value: Any): Any {
val v = if (value is UByte) value.toByte() else value
return super.notNullValueToDB(v)
}
}
/**
* Numeric column for storing 2-byte integers.
*/
class ShortColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.shortType()
override fun valueFromDB(value: Any): Short = when (value) {
is Short -> value
is Number -> value.toShort()
is String -> value.toShort()
else -> error("Unexpected value of type Short: $value of ${value::class.qualifiedName}")
}
}
/**
* Numeric column for storing unsigned 2-byte integers.
*/
@ExperimentalUnsignedTypes
class UShortColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.ushortType()
override fun valueFromDB(value: Any): UShort {
return when (value) {
is UShort -> value
is Short -> value.takeIf { it >= 0 }?.toUShort()
is Number -> value.toShort().takeIf { it >= 0 }?.toUShort()
is String -> value.toUShort()
else -> error("Unexpected value of type Short: $value of ${value::class.qualifiedName}")
} ?: error("negative value but type is UShort: $value")
}
override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) {
val v = if (value is UShort) value.toShort() else value
super.setParameter(stmt, index, v)
}
override fun notNullValueToDB(value: Any): Any {
val v = if (value is UShort) value.toShort() else value
return super.notNullValueToDB(v)
}
}
/**
* Numeric column for storing 4-byte integers.
*/
class IntegerColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.integerType()
override fun valueFromDB(value: Any): Int = when (value) {
is Int -> value
is Number -> value.toInt()
is String -> value.toInt()
else -> error("Unexpected value of type Int: $value of ${value::class.qualifiedName}")
}
}
/**
* Numeric column for storing unsigned 4-byte integers.
*/
@ExperimentalUnsignedTypes
class UIntegerColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.uintegerType()
override fun valueFromDB(value: Any): UInt {
return when (value) {
is UInt -> value
is Int -> value.takeIf { it >= 0 }?.toUInt()
is Number -> value.toInt().takeIf { it >= 0 }?.toUInt()
is String -> value.toUInt()
else -> error("Unexpected value of type Int: $value of ${value::class.qualifiedName}")
} ?: error("negative value but type is UInt: $value")
}
override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) {
val v = if (value is UInt) value.toInt() else value
super.setParameter(stmt, index, v)
}
override fun notNullValueToDB(value: Any): Any {
val v = if (value is UInt) value.toInt() else value
return super.notNullValueToDB(v)
}
}
/**
* Numeric column for storing 8-byte integers.
*/
class LongColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.longType()
override fun valueFromDB(value: Any): Long = when (value) {
is Long -> value
is Number -> value.toLong()
is String -> value.toLong()
else -> error("Unexpected value of type Long: $value of ${value::class.qualifiedName}")
}
}
/**
* Numeric column for storing unsigned 8-byte integers.
*/
@ExperimentalUnsignedTypes
class ULongColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.ulongType()
override fun valueFromDB(value: Any): ULong {
return when (value) {
is ULong -> value
is Long -> value.takeIf { it >= 0 }?.toULong()
is Number -> value.toLong().takeIf { it >= 0 }?.toULong()
is String -> value.toULong()
else -> error("Unexpected value of type Long: $value of ${value::class.qualifiedName}")
} ?: error("negative value but type is ULong: $value")
}
override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) {
val v = if (value is ULong) value.toLong() else value
super.setParameter(stmt, index, v)
}
override fun notNullValueToDB(value: Any): Any {
val v = if (value is ULong) value.toLong() else value
return super.notNullValueToDB(v)
}
}
/**
* Numeric column for storing 4-byte (single precision) floating-point numbers.
*/
class FloatColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.floatType()
override fun valueFromDB(value: Any): Float = when (value) {
is Float -> value
is Number -> value.toFloat()
is String -> value.toFloat()
else -> error("Unexpected value of type Float: $value of ${value::class.qualifiedName}")
}
}
/**
* Numeric column for storing 8-byte (double precision) floating-point numbers.
*/
class DoubleColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.doubleType()
override fun valueFromDB(value: Any): Double = when (value) {
is Double -> value
is Number -> value.toDouble()
is String -> value.toDouble()
else -> error("Unexpected value of type Double: $value of ${value::class.qualifiedName}")
}
}
/**
* Numeric column for storing numbers with the specified [precision] and [scale].
*/
class DecimalColumnType(
/** Total count of significant digits in the whole number. */
val precision: Int,
/** Count of decimal digits in the fractional part. */
val scale: Int
) : ColumnType() {
override fun sqlType(): String = "DECIMAL($precision, $scale)"
override fun readObject(rs: ResultSet, index: Int): Any? {
return rs.getBigDecimal(index)
}
override fun valueFromDB(value: Any): BigDecimal = when (value) {
is BigDecimal -> value
is Double -> {
if (value.isNaN())
error("Unexpected value of type Double: NaN of ${value::class.qualifiedName}")
else
value.toBigDecimal()
}
is Float -> {
if (value.isNaN())
error("Unexpected value of type Float: NaN of ${value::class.qualifiedName}")
else
value.toBigDecimal()
}
is Long -> value.toBigDecimal()
is Int -> value.toBigDecimal()
else -> error("Unexpected value of type Decimal: $value of ${value::class.qualifiedName}")
}.setScale(scale, RoundingMode.HALF_EVEN)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as DecimalColumnType
if (precision != other.precision) return false
if (scale != other.scale) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + precision
result = 31 * result + scale
return result
}
companion object {
internal val INSTANCE = DecimalColumnType(MathContext.DECIMAL64.precision, 20)
}
}
// Character columns
/**
* Character column for storing single characters.
*/
class CharacterColumnType : ColumnType() {
override fun sqlType(): String = "CHAR"
override fun valueFromDB(value: Any): Char = when (value) {
is Char -> value
is Number -> value.toChar()
is String -> value.single()
else -> error("Unexpected value of type Char: $value of ${value::class.qualifiedName}")
}
override fun notNullValueToDB(value: Any): Any = value.toString()
override fun nonNullValueToString(value: Any): String = "'$value'"
}
/**
* Base character column for storing strings using the specified text [collate] type.
*/
abstract class StringColumnType(
/** Returns the collate type used in by this column. */
val collate: String? = null
) : ColumnType() {
/** Returns the specified [value] with special characters escaped. */
protected fun escape(value: String): String = value.map { charactersToEscape[it] ?: it }.joinToString("")
override fun valueFromDB(value: Any): Any = when (value) {
is Clob -> value.characterStream.readText()
is ByteArray -> String(value)
else -> value
}
override fun nonNullValueToString(value: Any): String = buildString {
append('\'')
append(escape(value.toString()))
append('\'')
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as StringColumnType
if (collate != other.collate) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + (collate?.hashCode() ?: 0)
return result
}
companion object {
private val charactersToEscape = mapOf(
'\'' to "\'\'",
// '\"' to "\"\"", // no need to escape double quote as we put string in single quotes
'\r' to "\\r",
'\n' to "\\n"
)
}
}
/**
* Character column for storing strings with the exact [colLength] length using the specified [collate] type.
*/
open class CharColumnType(
/** Returns the maximum length of this column. */
val colLength: Int = 255,
collate: String? = null
) : StringColumnType(collate) {
override fun sqlType(): String = buildString {
append("CHAR($colLength)")
if (collate != null) {
append(" COLLATE ${escape(collate)}")
}
}
override fun validateValueBeforeUpdate(value: Any?) {
if (value is String) {
require(value.codePointCount(0, value.length) <= colLength) {
"Value '$value' can't be stored to database column because exceeds length ($colLength)"
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as CharColumnType
if (colLength != other.colLength) return false
if (collate != other.collate) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + colLength
return result
}
}
/**
* Character column for storing strings with the specified maximum [colLength] using the specified [collate] type.
*/
open class VarCharColumnType(
/** Returns the maximum length of this column. */
val colLength: Int = 255,
collate: String? = null
) : StringColumnType(collate) {
override fun sqlType(): String = buildString {
append("VARCHAR($colLength)")
if (collate != null) {
append(" COLLATE ${escape(collate)}")
}
}
override fun validateValueBeforeUpdate(value: Any?) {
if (value is String) {
require(value.codePointCount(0, value.length) <= colLength) {
"Value '$value' can't be stored to database column because exceeds length ($colLength)"
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as VarCharColumnType
if (colLength != other.colLength) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + colLength
return result
}
}
/**
* Character column for storing strings of arbitrary length using the specified [collate] type.
* [eagerLoading] means what content will be loaded immediately when data loaded from database.
*/
open class TextColumnType(collate: String? = null, val eagerLoading: Boolean = false) : StringColumnType(collate) {
override fun sqlType(): String = buildString {
append(currentDialect.dataTypeProvider.textType())
if (collate != null) {
append(" COLLATE ${escape(collate)}")
}
}
override fun readObject(rs: ResultSet, index: Int): Any? {
val value = super.readObject(rs, index)
return if (eagerLoading && value != null)
valueFromDB(value)
else
value
}
}
// Binary columns
/**
* Binary column for storing binary strings of variable and _unlimited_ length.
*/
open class BasicBinaryColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.binaryType()
override fun readObject(rs: ResultSet, index: Int): Any? = rs.getBytes(index)
override fun valueFromDB(value: Any): Any = when (value) {
is Blob -> value.binaryStream.use { it.readBytes() }
is InputStream -> value.use { it.readBytes() }
else -> value
}
override fun nonNullValueToString(value: Any): String = when (value) {
is ByteArray -> value.toString(Charsets.UTF_8)
else -> value.toString()
}
}
/**
* Binary column for storing binary strings of a specific [length].
*/
open class BinaryColumnType(
/** Returns the length of the column- */
val length: Int
) : BasicBinaryColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.binaryType(length)
override fun validateValueBeforeUpdate(value: Any?) {
if (value is ByteArray) {
require(value.size <= length) {
"Value '$value' can't be stored to database column because exceeds length ($length)"
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as BinaryColumnType
if (length != other.length) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + length
return result
}
}
/**
* Binary column for storing BLOBs.
*/
class BlobColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.blobType()
override fun valueFromDB(value: Any): ExposedBlob = when (value) {
is ExposedBlob -> value
is Blob -> ExposedBlob(value.binaryStream.use { it.readBytes() })
is InputStream -> ExposedBlob(value.use { it.readBytes() })
is ByteArray -> ExposedBlob(value)
else -> error("Unexpected value of type Blob: $value of ${value::class.qualifiedName}")
}
override fun notNullValueToDB(value: Any): Any {
return if (value is Blob) {
value.binaryStream
} else {
value
}
}
override fun nonNullValueToString(value: Any): String = "?"
override fun readObject(rs: ResultSet, index: Int) = rs.getBytes(index)?.let(::ExposedBlob)
override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) {
when (val toSetValue = (value as? ExposedBlob)?.bytes?.inputStream() ?: value) {
is InputStream -> stmt.setInputStream(index, toSetValue)
null, is Op.NULL -> stmt.setNull(index, this)
else -> super.setParameter(stmt, index, toSetValue)
}
}
}
/**
* Binary column for storing [UUID].
*/
class UUIDColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.uuidType()
override fun valueFromDB(value: Any): UUID = when {
value is UUID -> value
value is ByteArray -> ByteBuffer.wrap(value).let { b -> UUID(b.long, b.long) }
value is String && value.matches(uuidRegexp) -> UUID.fromString(value)
value is String -> ByteBuffer.wrap(value.toByteArray()).let { b -> UUID(b.long, b.long) }
else -> error("Unexpected value of type UUID: $value of ${value::class.qualifiedName}")
}
override fun notNullValueToDB(value: Any): Any = currentDialect.dataTypeProvider.uuidToDB(valueToUUID(value))
override fun nonNullValueToString(value: Any): String = "'${valueToUUID(value)}'"
private fun valueToUUID(value: Any): UUID = when (value) {
is UUID -> value
is String -> UUID.fromString(value)
is ByteArray -> ByteBuffer.wrap(value).let { UUID(it.long, it.long) }
else -> error("Unexpected value of type UUID: ${value.javaClass.canonicalName}")
}
override fun readObject(rs: ResultSet, index: Int): Any? = when (currentDialect) {
is MariaDBDialect -> rs.getBytes(index)
else -> super.readObject(rs, index)
}
companion object {
private val uuidRegexp = Regex("[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}", RegexOption.IGNORE_CASE)
}
}
// Boolean columns
/**
* Boolean column for storing boolean values.
*/
class BooleanColumnType : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.booleanType()
override fun valueFromDB(value: Any): Boolean = when (value) {
is Number -> value.toLong() != 0L
is String -> currentDialect.dataTypeProvider.booleanFromStringToBoolean(value)
else -> value.toString().toBoolean()
}
override fun nonNullValueToString(value: Any): String = currentDialect.dataTypeProvider.booleanToStatementString(value as Boolean)
companion object {
internal val INSTANCE = BooleanColumnType()
}
}
// Enumeration columns
/**
* Enumeration column for storing enums of type [klass] by their ordinal.
*/
class EnumerationColumnType<T : Enum<T>>(
/** Returns the enum class used in this column type. */
val klass: KClass<T>
) : ColumnType() {
override fun sqlType(): String = currentDialect.dataTypeProvider.integerType()
private val enumConstants by lazy { klass.java.enumConstants!! }
@Suppress("UNCHECKED_CAST")
override fun valueFromDB(value: Any): T = when (value) {
is Number -> enumConstants[value.toInt()]
is Enum<*> -> value as T
else -> error("$value of ${value::class.qualifiedName} is not valid for enum ${klass.simpleName}")
}
override fun notNullValueToDB(value: Any): Int = when (value) {
is Int -> value
is Enum<*> -> value.ordinal
else -> error("$value of ${value::class.qualifiedName} is not valid for enum ${klass.simpleName}")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as EnumerationColumnType<*>
if (klass != other.klass) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + klass.hashCode()
return result
}
}
/**
* Enumeration column for storing enums of type [klass] by their name.
*/
class EnumerationNameColumnType<T : Enum<T>>(
/** Returns the enum class used in this column type. */
val klass: KClass<T>,
colLength: Int
) : VarCharColumnType(colLength) {
private val enumConstants by lazy { klass.java.enumConstants!!.associateBy { it.name } }
@Suppress("UNCHECKED_CAST")
override fun valueFromDB(value: Any): T = when (value) {
is String -> enumConstants[value] ?: error("$value can't be associated with any from enum ${klass.qualifiedName}")
is Enum<*> -> value as T
else -> error("$value of ${value::class.qualifiedName} is not valid for enum ${klass.qualifiedName}")
}
override fun notNullValueToDB(value: Any): Any = when (value) {
is String -> super.notNullValueToDB(value)
is Enum<*> -> super.notNullValueToDB(value.name)
else -> error("$value of ${value::class.qualifiedName} is not valid for enum ${klass.qualifiedName}")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as EnumerationNameColumnType<*>
if (klass != other.klass) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + klass.hashCode()
return result
}
}
// Date/Time columns
/**
* Marker interface for date/datetime related column types.
**/
interface IDateColumnType {
val hasTimePart: Boolean
}