I have web app chemical compound database built using phoenix framework, liveview and postgresql. Write highly efficient, high performance and cpncurrent code for user interface pages using liveview. Homepage with realtime autocomplete search bar suggestions, search results page and detailed compound view page. Search bar should be globally reusable component. Make sure it is compliant with best practices and most recent versions. Follow functional programming paradigm.
Assistant
Creating a highly efficient, high-performance, and concurrent web application using Phoenix LiveView involves careful structuring of your components, optimal database interactions, and leveraging LiveView’s real-time capabilities. Below is a comprehensive guide to building the required user interface pages for your chemical compound database, adhering to best practices, functional programming paradigms, and the latest versions of the Phoenix Framework.
First, define your Compound schema to interact with the compounds table in PostgreSQL.
elixir
# lib/chembd/chemistry/compound.ex
defmodule ChemDB.Chemistry.Compound do
use Ecto.Schema
import Ecto.Changeset
schema "compounds" do
field :name, :string
field :formula, :string
field :molecular_weight, :float
field :description, :string
# Add other relevant fields
timestamps()
end
@doc false
def changeset(compound, attrs) do
compound
|> cast(attrs, [:name, :formula, :molecular_weight, :description])
|> validate_required([:name, :formula])
end
end
Ensure you have appropriate indexes on the name and formula fields to optimize search queries:
elixir
# priv/repo/migrations/xxxx_create_compounds.exs
defmodule ChemDB.Repo.Migrations.CreateCompounds do
use Ecto.Migration
def change do
create table(:compounds) do
add :name, :string, null: false
add :formula, :string, null: false
add :molecular_weight, :float
add :description, :text
timestamps()
end
create index(:compounds, [:name])
create index(:compounds, [:formula])
end
end
Run the migration:
bash
mix ecto.migrate
Reusable Search Bar Component
Creating a reusable search bar component enhances maintainability and consistency across different pages.
elixir
# lib/chemd_db_web/live/components/search_bar_component.ex
defmodule ChemDBWeb.Live.Components.SearchBarComponent do
use ChemDBWeb, :live_component
alias ChemDB.Chemistry
@impl true
def mount(socket) do
{:ok, assign(socket, query: "", suggestions: [])}
end
@impl true
def update(assigns, socket) do
{:ok, assign(socket, assigns)}
end
@impl true
def handle_event("update", %{"query" => query}, socket) do
suggestions = Chemistry.autocomplete_compounds(query)
{:noreply, assign(socket, query: query, suggestions: suggestions)}
end
@impl true
def handle_event("select_suggestion", %{"suggestion" => suggestion}, socket) do
# Handle the selection, possibly redirecting to the search results
{:noreply,
push_redirect(socket, to: Routes.search_results_path(socket, :index, query: suggestion))}
end
def render(assigns) do
~H"""
<div phx-update="ignore" class="search-bar">
<input
type="text"
name="query"
value={@query}
placeholder="Search compounds..."
phx-debounce="300"
phx-keyup="update"
phx-target={@myself}
autocomplete="off"
/>
<ul class="suggestions" id="suggestions-<%= @id %>">
<%= for suggestion <- @suggestions do %>
<li
phx-click="select_suggestion"
phx-value-suggestion={suggestion.name}
phx-target={@myself}
>
<%= suggestion.name %> (<%= suggestion.formula %>)
</li>
<% end %>
</ul>
</div>
"""
end
end
Autocomplete Function
Implement the autocomplete logic in your context to efficiently fetch suggestions.
elixir
# lib/chemd_db/chemistry.ex
defmodule ChemDB.Chemistry do
import Ecto.Query, warn: false
alias ChemDB.Repo
alias ChemDB.Chemistry.Compound
@doc """
Returns a list of compounds matching the autocomplete query.
"""
def autocomplete_compounds(query) when is_binary(query) do
pattern = "%#{String.trim(query)}%"
Compound
|> where([c], ilike(c.name, ^pattern) or ilike(c.formula, ^pattern))
|> limit(10)
|> select([c], %{name: c.name, formula: c.formula, id: c.id})
|> Repo.all()
end
# Other context functions...
end
Note: Using ilike with indexed columns and limiting results optimizes performance. For even better performance on large datasets, consider using full-text search or trigram indexes.
Homepage with Real-time Autocomplete
The homepage will include the reusable search bar component. Here, we define the LiveView for the homepage.
elixir
# lib/chembd_web/live/homepage_live.ex
defmodule ChemDBWeb.Live.HomepageLive do
use ChemDBWeb, :live_view
alias ChemDBWeb.Live.Components.SearchBarComponent
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def render(assigns) do
~H"""
<div class="homepage">
<h1>Welcome to ChemDB</h1>
<.live_component
module={SearchBarComponent}
id="global_search_bar"
/>
<!-- Additional homepage content -->
</div>
"""
end
end
Routing
Add the homepage route.
elixir
# lib/chembd_web/router.ex
defmodule ChemDBWeb.Router do
use ChemDBWeb, :router
import Phoenix.LiveView.Router
pipeline :browser do
# existing plugs...
end
scope "/", ChemDBWeb do
pipe_through :browser
live "/", Live.HomepageLive, :index
live "/search", Live.SearchResultsLive, :index
live "/compound/:id", Live.CompoundDetailLive, :show
# Other routes...
end
end
Search Results Page
The search results page displays the list of compounds matching the search query. It uses the reusable search bar component for consistency and allows users to refine their search.
elixir
# lib/chemdb_web/live/search_results_live.ex
defmodule ChemDBWeb.Live.SearchResultsLive do
use ChemDBWeb, :live_view
alias ChemDBWeb.Live.Components.SearchBarComponent
alias ChemDB.Chemistry
@impl true
def mount(_params, _session, socket) do
{:ok, assign(socket, query: "", compounds: [])}
end
@impl true
def handle_params(%{"query" => query}, _uri, socket) do
compounds = Chemistry.search_compounds(query)
{:noreply, assign(socket, query: query, compounds: compounds)}
end
@impl true
def render(assigns) do
~H"""
<div class="search-results">
<.live_component
module={SearchBarComponent}
id="search_bar_results"
query={@query}
/>
<h2>Search Results for "<%= @query %>"</h2>
<ul>
<%= for compound <- @compounds do %>
<li>
<a href={Routes.compound_detail_path(@socket, :show, compound.id)}>
<%= compound.name %> (<%= compound.formula %>)
</a>
</li>
<% end %>
</ul>
<%= if @compounds == [] do %>
<p>No compounds found matching your query.</p>
<% end %>
</div>
"""
end
end
Search Function
Define the search functionality in the context.
elixir
# lib/chemd_db/chemistry.ex
defmodule ChemDB.Chemistry do
# Existing imports and aliases...
@doc """
Searches for compounds matching the query in name or formula.
"""
def search_compounds(query) when is_binary(query) do
pattern = "%#{String.trim(query)}%"
Compound
|> where([c], ilike(c.name, ^pattern) or ilike(c.formula, ^pattern))
|> order_by(:name)
|> Repo.all()
end
# Other context functions...
end
Detailed Compound View Page
This page provides detailed information about a specific compound.
elixir
# lib/chemdb_web/live/compound_detail_live.ex
defmodule ChemDBWeb.Live.CompoundDetailLive do
use ChemDBWeb, :live_view
alias ChemDB.Chemistry
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(%{"id" => id}, _uri, socket) do
case Chemistry.get_compound!(id) do
nil ->
{:noreply, push_redirect(socket, to: Routes.homepage_path(socket, :index))}
compound ->
{:noreply, assign(socket, compound: compound)}
end
end
@impl true
def render(assigns) do
~H"""
<div class="compound-detail">
<h1><%= @compound.name %> (<%= @compound.formula %>)</h1>
<p><strong>Molecular Weight:</strong> <%= @compound.molecular_weight %> g/mol</p>
<p><strong>Description:</strong> <%= @compound.description %></p>
<!-- Add more detailed information as needed -->
<a href={Routes.search_results_path(@socket, :index, query: @compound.name)}>Back to Search Results</a>
</div>
"""
end
end
Getter Function
Implement the function to retrieve a compound by ID.
elixir
# lib/chemd_db/chemistry.ex
defmodule ChemDB.Chemistry do
# Existing imports and aliases...
@doc """
Retrieves a compound by ID.
"""
def get_compound!(id) do
Repo.get!(Compound, id)
rescue
Ecto.NoResultsError -> nil
end
# Other context functions...
end
Optimizations and Best Practices
Caching Frequent Queries:
Use caching solutions like ETS or external caches (e.g., Redis) for frequently accessed data to reduce database load.
Debouncing User Input:
The search bar uses phx-debounce="300" to minimize the number of autocomplete requests, enhancing performance.
Efficient Database Queries:
Use select to fetch only necessary fields.
Implement pagination on search results to handle large datasets.
Utilize database indexes effectively.
Concurrency:
Phoenix and Elixir are inherently concurrent. Ensure that long-running tasks are handled asynchronously if needed, using Task or background processing with tools like Oban.
Component Reusability:
The search bar is a reusable LiveComponent, promoting DRY (Don't Repeat Yourself) principles and easier maintenance.
Error Handling:
Handle potential errors gracefully, such as invalid search queries or missing compound data, to enhance user experience.
Responsive Design:
Ensure that the UI components are responsive and accessible across different devices and screen sizes.
Security:
Validate and sanitize all user inputs.
Protect against common web vulnerabilities (e.g., SQL injection, XSS).
Testing:
Write comprehensive tests for your LiveViews and components to ensure reliability and prevent regressions.
Functional Programming Paradigm:
Emphasize pure functions within your context modules.
Avoid side effects where possible.
Utilize pattern matching and immutable data structures to enhance code clarity and reliability.
By following this structured approach, you can build a performant, maintainable, and scalable chemical compound database web application using Phoenix LiveView. Tailor each component further based on specific requirements and iterative testing to ensure optimal performance and user experience.