AugustNagro / magnum

A 'new look' for database access in Scala
Apache License 2.0
153 stars 10 forks source link

Question: is there an example where db column names are different from case class property names? #14

Closed dxxvi closed 11 months ago

AugustNagro commented 1 year ago

Yes; in this example SqlNameMapper.CamelToSnakeCase maps the class & field names from Camel case to Snake case:

@Table(PostgresDbType, SqlNameMapper.CamelToSnakeCase)
case class User(
  @Id id: Long,
  firstName: Option[String],
  lastName: String,
  created: OffsetDateTime
) derives DbCodec

The corresponding sql table could be:

create table user (
    id bigint primary key,
    first_name text,
    last_name text not null,
    created timestamptz not null
);

There's other implementations of SqlNameMapper, and users can create their own as well.

To change individual columns you can use the @SqlName(String) annotation:

@Table(PostgresDbType, SqlNameMapper.CamelToSnakeCase)
@SqlName(config.schema + ".my_user")
case class User(
  @Id id: Long,
  firstName: Option[String],
  @SqlName("usr_last_name") lastName: String,
  created: OffsetDateTime
) derives DbCodec

More documentation is in https://github.com/AugustNagro/magnum#immutable-repositories :)

AugustNagro commented 11 months ago

Hi @dxxvi feel free to re-open if unresolved.