EvidentSolutions / dalesbred

Dalesbred - a database access library for Java
https://dalesbred.org
MIT License
54 stars 15 forks source link

SqlQuery: Call toString() on args #49

Closed niclas-lindgren closed 3 years ago

niclas-lindgren commented 3 years ago

version of Dalesbred and JDK: Dalesbred 1.3.0, Java 14/15 versions of other libraries if using Dalesbred's integration features: Nil database product and version MySql 5 InnoDB used JDBC driver and important connection settings mysql-connector-java 5.1.44

Description When running a query against MySql as specified above using UUID, the object itself (objecttype/hash) is passed as argument and not the UUID. Seems to be working for example on Sqlite

I suggest calling .toString on all args passed?

Reproduce

CREATE TABLE IF NOT EXISTS `State`
(
    `id`             varchar(36)  NOT NULL,
    `foo`                varchar(100) NOT NULL
)

UUID id = UUID.fromString("4a221220-330a-42e1-8460-ee4f39debd92");

 db.update("""
                    UPDATE State
                    SET foo = ?
                    WHERE id = ?
                """, "bar", id);
komu commented 3 years ago

That's not possible because most database drivers care about the column types. If a column expects an integer, you can't pass "42" instead of 42. Furthermore how would you convert strings back to arbitrary objects?

You can, however, register arbitrary mapping how a type is represented in database. If you wish to represent UUIDs as strings, you can say:

db.getTypeConversionRegistry().registerConversions(String.class, UUID.class, UUID::fromString, UUID::toString);

This registers conversions both ways so you can freely use UUIDs in your code and they will be stored as UUIDs in database.

Does this answer your need?

This is not really related to Dalesbred, but doesn't MySQL have an UUID type like PostgreSQL? UUID only has128 bits of information whereas varchar(36) will use more, bloating indices. PostgreSQL handles UUIDs as strings in JDBC level, but internally stores them in an optimized format.

niclas-lindgren commented 3 years ago

Ok thank you for the reply, that makes of course sense :-)