Concatenate database field value from two database fields

Here is as example of my table name. Is it possible to set a database field default value to data from two fields.
For example
schema “tbl_ticket” do

field :bus_name, :string

field :issue, :string

field :platform, :string

field :rep_name, :string , default: platform<>issue

field :tel, :integer

field :issue_status, :string

Pardon my syntax it was just meant to show you an idea of what i wanted to achieve.

You don’t mention what database you’re using, but I’ll make an educated guess and describe Postgres for now because it’s what I know better than the rest.

You have a few options, two of which are “handle this with your changesets” and “handle this at the database”, and you might have stronger motives to choose one or the other.

With changesets, you can have arbitrarily complex defaulting rules as long as you are either 1. tolerant of missing information or 2. extremely confident that all inserts and updates will flow through changesets. You can use Ecto.Changeset.get_change to inspect if either of the contributing fields have been included, then use Ecto.Changeset.put_change to inject a change to the derived column.

You can instead use a database trigger to write a calculated value to a column that was not otherwise provided during the INSERT/UPDATE, and this can base its calculation on other existing columns. This can be bypassed but you have to explicitly intend to do so, and is otherwise enforced by the database behavior and will fail the insert if it produces an invalid row. Your main limitation here is that you need to be able to express the calculation in PL/pgSQL or another supported trigger language.

Finally, you can set 0-arity function calls (i.e. uuid_generate_v4 from the uuid-ossp extension) as a column default in Postgres, but they cannot take any arguments or inspect other columns. When changing an existing column to add or change a default, if you use a function call, there is nuance around whether or not that will write every row in your table so please refer to the docs. The behavior for this changed partially between v10 and v11+, and may not require a full table write unless the function is volatile.

2 Likes