defp to_live_select_option(%{label: label, value: value}) do
%{label: label, value: value}
end
end
lib/moldb/compounds/compound.ex
defmodule Moldb.Compounds.Compound do
@moduledoc """
Module for handling compounds in Moldb.
"""
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, UUIDv7, autogenerate: true}
schema "compounds" do
field :iupac_name, :string
field :molecular_formula, :string
field :molecular_weight, :decimal
field :canonical_smiles, :string
field :inchi, :string
field :inchi_key, :string
defmodule Moldb.Compounds.Substance do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, UUIDv7, autogenerate: true}
schema "substances" do
field :substance_name, :string
field :physical_state, :string
field :salt_form, :string
field :stereochemistry, :string
@doc false
def changeset(substance, attrs) do
substance
|> cast(attrs, [:substance_name, :physical_state, :salt_form, :stereochemistry, :compound_id])
|> validate_required([:substance_name, :compound_id])
|> foreign_key_constraint(:compound_id)
end
end
lib/moldb/compounds.ex
defmodule Moldb.Compounds do
@moduledoc """
The Compounds context handles all interactions with compounds and substances in the database.
"""
import Ecto.Query, warn: false
alias Moldb.Repo
alias Moldb.Compounds.{Compound, Substance}
Compound Functions
@doc """
Returns the list of compounds.
"""
def list_compounds, do: Repo.all(Compound)
@doc """
Gets a single compound.
Raises Ecto.NoResultsError if the Compound does not exist.
"""
def get_compound!(id), do: Repo.get!(Compound, id)
defmodule Moldb.Compounds.CompoundProperty do
@moduledoc """
Defines the CompoundProperty schema and changeset functions.
"""
use Ecto.Schema
import Ecto.Changeset
schema "compound_properties" do
field :property_name, :string
field :property_value, :decimal
field :property_unit, :string
field :property_category, :string
defmodule Moldb.Compounds.CompoundSynonym do
@moduledoc """
Defines the CompoundSynonym schema and changeset functions.
"""
use Ecto.Schema
import Ecto.Changeset
"""
def get_user_by_email_and_password(email, password)
when is_binary(email) and is_binary(password) do
user = Repo.get_by(User, email: email)
if User.valid_password?(user, password), do: user
end
@doc """
Gets a single user.
Raises Ecto.NoResultsError if the User does not exist.
"""
def apply_user_email(user, password, attrs) do
user
|> User.email_changeset(attrs)
|> User.validate_current_password(password)
|> Ecto.Changeset.apply_action(:update)
end
@doc """
Updates the user email using the given token.
If the token matches, the user email is updated and the token is deleted.
The confirmed_at date is also updated to the current time.
"""
def update_user_email(user, token) do
context = "change:#{user.email}"
code
with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
%UserToken{sent_to: email} <- Repo.one(query),
{:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do
:ok
else
_ -> :error
end
end
defp user_email_multi(user, email, context) do
changeset =
user
|> User.email_changeset(%{email: email})
|> User.confirm_changeset()
"""
def update_user_password(user, password, attrs) do
changeset =
user
|> User.password_changeset(attrs)
|> User.validate_current_password(password)
code
Ecto.Multi.new()
|> Ecto.Multi.update(:user, changeset)
|> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, :all))
|> Repo.transaction()
|> case do
{:ok, %{user: user}} -> {:ok, user}
{:error, :user, changeset, _} -> {:error, changeset}
end
end
Session
@doc """
Generates a session token.
"""
def generate_user_session_token(user) do
{token, user_token} = UserToken.build_session_token(user)
Repo.insert!(user_token)
token
end
@doc """
Gets the user with the given signed token.
"""
def get_user_by_session_token(token) do
{:ok, query} = UserToken.verify_session_token_query(token)
Repo.one(query)
end
@doc """
Deletes the signed token with the given context.
"""
def delete_user_session_token(token) do
Repo.delete_all(UserToken.by_token_and_context_query(token, "session"))
:ok
end
Confirmation
@doc ~S"""
Delivers the confirmation email instructions to the given user.
"""
def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun)
when is_function(confirmation_url_fun, 1) do
if user.confirmed_at do
{:error, :already_confirmed}
else
{encoded_token, user_token} = UserToken.build_email_token(user, "confirm")
Repo.insert!(user_token)
UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
end
end
@doc """
Confirms a user by the given token.
If the token matches, the user account is marked as confirmed
and the token is deleted.
"""
def confirm_user(token) do
with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"),
%User{} = user <- Repo.one(query),
{:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do
{:ok, user}
else
_ -> :error
end
end
defp confirm_user_multi(user) do
Ecto.Multi.new()
|> Ecto.Multi.update(:user, User.confirm_changeset(user))
|> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, ["confirm"]))
end
Reset password
@doc ~S"""
Delivers the reset password email to the given user.
"""
def get_user_by_reset_password_token(token) do
with {:ok, query} <- UserToken.verify_email_token_query(token, "reset_password"),
%User{} = user <- Repo.one(query) do
user
else
_ -> nil
end
end
@doc """
Resets the user password.
Examples
code
iex> reset_user_password(user, %{password: "new long password", password_confirmation: "new long password"})
{:ok, %User{}}
iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"})
{:error, %Ecto.Changeset{}}
"""
def reset_user_password(user, attrs) do
Ecto.Multi.new()
|> Ecto.Multi.update(:user, User.password_changeset(user, attrs))
|> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, :all))
|> Repo.transaction()
|> case do
{:ok, %{user: user}} -> {:ok, user}
{:error, :user, changeset, _} -> {:error, changeset}
end
end
end
Review and analyze
Review and Analysis
Overview:
The provided code snippets are from an Elixir/Phoenix web application that implements a compound search functionality using Phoenix LiveView and the live_select component. The application allows users to search for compounds and substances by name, displaying matching results dynamically as the user types.
Calls Search.search_options/1 with the search_text to get matching options.
Sends an update to the live_select component with new options.
Updates the form with the current search_text.
"change" Event
elixir
def handle_event("change", %{"compound" => compound}, socket) do
{:noreply, assign(socket, form: to_form(%{"compound" => compound}))}
end
Analysis:
Updates the form data when changes occur.
Ensures the form's "compound" field remains in sync with user input.
"blur" Event
elixir
def handle_event("blur", %{"id" => "compound-search"}, socket) do
send_update(LiveSelect.Component, id: "compound-search", options: [])
{:noreply, socket}
end
Analysis:
Clears the options when the live_select component loses focus.
Helps prevent stale suggestions from lingering.
"clear" Event
elixir
Suggestions:
Form Handling:
Ensure that to_form/1 correctly converts the data structure expected by the template.
Consider initializing the form with %{} instead of %{"compound" => ""} if no default value is needed.
Event Names:
Verify that the event names correspond to the events triggered by the live_select component.
Ensure consistency in handling events to prevent unexpected behavior.
Error Handling:
Incorporate error handling in case Search.search_options/1 returns an error.
Log or display any errors to assist with debugging.
3. Search Module: search.ex
elixir
defmodule Moldb.Search do
...
@search_limit 10
@spec search_options(String.t()) :: [map()]
def search_options(""), do: []
def search_options(query) do
query
|> search_query()
|> Repo.all()
|> Enum.map(&to_live_select_option/1)
|> Enum.sort_by(& &1.label)
end
defp search_query(query) do
compound_query = from(c in Compound, where: ilike(c.iupac_name, ^"%#{query}%"), select: %{label: c.iupac_name, value: c.iupac_name})
substance_query = from(s in Substance, where: ilike(s.substance_name, ^"%#{query}%"), select: %{label: s.substance_name, value: s.substance_name})
compound_query
|> union_all(^substance_query)
|> limit(@search_limit)
end
defp to_live_select_option(%{label: label, value: value}) do
%{label: label, value: value}
end
end
Analysis:
search_options/1 Function:
Returns an empty list for an empty query.
For non-empty queries, constructs a search query and retrieves matching records.
Maps the results to the expected format for live_select.
Sorts the options alphabetically by label.
search_query/1 Function:
Searches both Compound and Substance tables using case-insensitive patterns.
Uses ilike with wildcards ("%#{query}%") to match any part of the name.
Combines the results using union_all.
Limits the total results to @search_limit (10).
Suggestions:
Performance Optimization:
Indexing:
Ensure that indexes are present on iupac_name and substance_name fields to speed up searches.
Full-Text Search:
Consider using PostgreSQL's full-text search capabilities for more advanced and performant searching.
Alternatively, use the tsvector and tsquery functionality for more efficient querying.
Query Improvement:
Wildcard Usage:
Leading wildcards ("%#{query}%") can prevent the database from using indexes effectively.
Recommendation: Remove the leading wildcard to improve performance if searching for names that start with the query is acceptable.
elixir
ilike(c.iupac_name, ^"#{query}%")
Separate Limits:
Currently, the limit is applied after the union, which might result in unbalanced results from each table.
Recommendation: Apply limits to each subquery before the union if you want to ensure a mix of results from both tables.
elixir
compound_query = from(c in Compound, ..., limit: @search_limit)
substance_query = from(s in Substance, ..., limit: @search_limit)
Input Sanitization:
Trim whitespace and downcase the query string to standardize searches.
Handle special characters that might interfere with the query.
Error Handling:
Ensure that exceptions in database queries are properly handled to prevent crashes.
4. Schema Modules
Compound Schema: compounds/compound.ex
elixir
defmodule Moldb.Compounds.Compound do
...
schema "compounds" do
field :iupac_name, :string
field :molecular_formula, :string
field :molecular_weight, :decimal
field :canonical_smiles, :string
field :inchi, :string
field :inchi_key, :string
has_many :substances, Moldb.Compounds.Substance
has_many :properties, Moldb.Compounds.CompoundProperty
has_many :synonyms, Moldb.Compounds.CompoundSynonym
timestamps(type: :utc_datetime)
end
...
end
Analysis:
Defines the Compound schema with relevant chemical fields.
Associations:
has_many relationships with Substance, CompoundProperty, and CompoundSynonym.
Uses UUIDv7 for the primary key, which is a UUID based on the new UUID version 7.
Suggestions:
Data Types:
molecular_weight: Consider using :float if high precision isn't required. If precision is crucial, ensure the decimal type has sufficient scale.
Indexes:
Add indexes to frequently searched fields like iupac_name, canonical_smiles, and inchi_key.
Validation and Constraints:
Ensure all required fields have appropriate validations.
Unique constraints are correctly set for canonical_smiles, inchi, and inchi_key.
Consistency:
Verify that the database migrations match the schema definitions, including field types and constraints.
Substance Schema: compounds/substance.ex
elixir
defmodule Moldb.Compounds.Substance do
...
schema "substances" do
field :substance_name, :string
field :physical_state, :string
field :salt_form, :string
field :stereochemistry, :string
belongs_to :compound, Moldb.Compounds.Compound, type: UUIDv7
timestamps(type: :utc_datetime)
end
...
end
Analysis:
Defines the Substance schema, related to Compound.
Uses UUIDv7 for primary key and foreign key to Compound.
Suggestions:
Field Validations:
Ensure that optional fields like physical_state, salt_form, and stereochemistry are handled appropriately if they can be nil.
Association Integrity:
Verify that belongs_to :compound is correctly set with the appropriate foreign key type.
5. Context Module: compounds.ex
Analysis:
Provides a context for managing Compound and Substance entities.
Includes CRUD functions for both schemas.
Helper functions like compound_name/1 and substance_name/1 provide default values when names are missing.
Preloads associations where necessary.
Suggestions:
Function Documentation:
Ensure all public functions have up-to-date documentation (@doc) for maintainability.
Error Handling:
Add error handling for cases where associated records might not exist.
For example, handle nil cases in compound_name/1 and substance_name/1.
Optimizations:
Use Repo.preload/2 selectively to avoid unnecessary data loading.
Consider using Repo.one/1 or Repo.get_by/3 where appropriate.
6. Mix Project Configuration: mix.exs
Dependencies:
elixir
defp deps do
[
...
{:live_select, "~> 1.4"}
]
end
Analysis:
The live_select dependency is included, which provides the live select component functionality.
Uses uuidv7 for UUID version 7 support.
Development and testing tools (sobelow, ex_doc, dialyxir, credo) are properly listed under appropriate environments.
Suggestions:
Dependency Versions:
Ensure that all dependencies are compatible with the versions of Elixir and Phoenix being used.
Check if phoenix_live_view can be upgraded from the release candidate version to a stable release.
elixir
{:phoenix_live_view, "~> 0.18.18"}
Future-Proofing:
Keep an eye on updates for live_select and other dependencies for bug fixes and new features.
Assets Pipeline:
Ensure that asset management tools (esbuild, tailwind) are properly configured and up-to-date.
7. Additional Modules
CompoundProperty and CompoundSynonym Schemas
Analysis:
Define additional schemas for compound properties and synonyms.
Include proper validations and associations to Compound.
Use UUIDv7 for primary keys.
Suggestions:
Data Integrity:
Ensure that the constraints and validations align with business logic.
For example, enforce uniqueness on synonyms if required.
Testing:
Write tests to cover these modules, ensuring they behave as expected with various inputs.
8. Accounts Module: accounts.ex
Analysis:
Manages user authentication and account features.
Handles password hashing, session tokens, email confirmations, and password resets.
Suggestions:
Security:
Regularly review authentication flows for security vulnerabilities.
Use libraries like sobelow to scan for common security issues.
User Experience:
Ensure that error messages and notifications provide helpful guidance to users without exposing sensitive information.
General Recommendations
1. Testing:
Unit Tests:
Write comprehensive unit tests for all modules and functions.
Cover edge cases, such as empty searches, special characters, and large input sizes.
Integration Tests:
Test the search functionality end-to-end to ensure that the UI, LiveView handlers, and database queries work seamlessly together.
2. Performance:
Database Optimization:
Regularly monitor query performance, especially for search queries.
Use tools like Ecto.Query logging and explain analyze in PostgreSQL.
Caching:
Consider caching frequently accessed data if necessary.
3. User Experience:
Feedback Mechanisms:
Provide visual feedback while search results are loading.
Display a message when no results are found.
Accessibility:
Ensure that components are accessible (e.g., keyboard navigation, screen reader support).
4. Code Quality:
Consistency:
Follow consistent coding styles and conventions throughout the codebase.
Utilize tools like credo for code analysis and style enforcement.
Documentation:
Keep module and function documentation up-to-date.
Use @spec annotations for function specifications to aid tools like Dialyzer.
5. Security:
Input Validation:
Sanitize and validate all user inputs to prevent injection attacks and other vulnerabilities.
Even though Ecto parameterizes queries to prevent SQL injection, it's good practice to validate input lengths and characters.
Dependency Updates:
Regularly update dependencies to include security patches and improvements.
Conclusion:
The provided code demonstrates a solid foundation for a real-time compound search feature using Phoenix LiveView. By addressing the suggestions above, you can enhance the application's performance, maintainability, and user experience. Regular reviews, testing, and updates will ensure the application remains robust and secure as it evolves.