sqldelight icon indicating copy to clipboard operation
sqldelight copied to clipboard

Generated data class should override 'equals()' and 'hashCode()' if it has a ByteArray property (BLOB)

Open xit0c opened this issue 2 months ago • 0 comments

Description

A table like the following:

CREATE TABLE myTable (
    id INTEGER PRIMARY KEY ASC NOT NULL,
    rawData BLOB NOT NULL
);

Generates a data class like this:

public data class MyTable(
  public val id: Long,
  public val rawData: ByteArray
)

Which will fail to properly check equality beacuse of the Array type (even Android Studio warns you about it when you create a data class with a ByteArray property in non-generated code, I'll attach the screenshot).

image

So the data class should override equals() and hashCode() and use .contentEquals and .contentHashCode respectively on its ByteArray properties, resulting in something like the following:

public data class MyTable(
    public val id: Long,
    public val rawData: ByteArray
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as MyTable

        if (id != other.id) return false
        if (!rawData.contentEquals(other.rawData)) return false

        return true
    }

    override fun hashCode(): Int {
        var result = id.hashCode()
        result = 31 * result + rawData.contentHashCode()
        return result
    }
}

xit0c avatar May 07 '24 15:05 xit0c