Add support for named addresses (#590)
parent
050870f8b4
commit
cade255e15
@ -0,0 +1,42 @@ |
||||
defmodule Explorer.Chain.Address.Name do |
||||
@moduledoc """ |
||||
Represents a name for an Address. |
||||
""" |
||||
|
||||
use Explorer.Schema |
||||
|
||||
alias Explorer.Chain.{Address, Hash} |
||||
|
||||
@typedoc """ |
||||
* `address` - the `t:Explorer.Chain.Address.t/0` with `value` at end of `block_number`. |
||||
* `address_hash` - foreign key for `address`. |
||||
* `name` - name for the address |
||||
* `primary` - flag for if the name is the primary name for the address |
||||
""" |
||||
@type t :: %__MODULE__{ |
||||
address: %Ecto.Association.NotLoaded{} | Address.t(), |
||||
address_hash: Hash.Address.t(), |
||||
name: String.t(), |
||||
primary: boolean() |
||||
} |
||||
|
||||
@primary_key false |
||||
schema "address_names" do |
||||
field(:name, :string) |
||||
field(:primary, :boolean) |
||||
belongs_to(:address, Address, foreign_key: :address_hash, references: :hash, type: Hash.Address) |
||||
|
||||
timestamps() |
||||
end |
||||
|
||||
@required_fields ~w(address_hash name)a |
||||
@optional_fields ~w(primary)a |
||||
@allowed_fields @required_fields ++ @optional_fields |
||||
|
||||
def changeset(%__MODULE__{} = struct, params \\ %{}) do |
||||
struct |
||||
|> cast(params, @allowed_fields) |
||||
|> validate_required(@required_fields) |
||||
|> foreign_key_constraint(:address_hash) |
||||
end |
||||
end |
@ -0,0 +1,33 @@ |
||||
defmodule Explorer.Repo.Migrations.CreateAddressNames do |
||||
use Ecto.Migration |
||||
|
||||
def change do |
||||
create table(:address_names, primary_key: false) do |
||||
add(:address_hash, :bytea, null: false) |
||||
add(:name, :string, null: false) |
||||
add(:primary, :boolean, null: false, default: false) |
||||
|
||||
timestamps() |
||||
end |
||||
|
||||
# Only 1 primary per address |
||||
create(unique_index(:address_names, [:address_hash], where: ~s|"primary" = true|)) |
||||
# No duplicate names per address |
||||
create(unique_index(:address_names, [:address_hash, :name], name: :unique_address_names)) |
||||
|
||||
insert_names_from_existing_data_query = """ |
||||
INSERT INTO address_names (address_hash, name, "primary", inserted_at, updated_at) |
||||
( |
||||
SELECT address_hash, name, true, NOW(), NOW() |
||||
FROM smart_contracts WHERE name IS NOT NULL |
||||
|
||||
UNION |
||||
|
||||
SELECT contract_address_hash, name, false, NOW(), NOW() |
||||
FROM tokens WHERE name IS NOT NULL |
||||
); |
||||
""" |
||||
|
||||
execute(insert_names_from_existing_data_query) |
||||
end |
||||
end |
Loading…
Reference in new issue