Fix database creation on deployment

- Add create_database/0 function to handle database creation before migrations
- Make DeviceCache handle missing tables gracefully on startup
- Retry device loading after 5 seconds if initial load fails
- Prevent deployment failures when database doesn't exist yet

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Graham McIntire 2025-07-21 13:05:23 -05:00
parent f4aabf56c0
commit cd69de5131
No known key found for this signature in database
2 changed files with 43 additions and 8 deletions

View file

@ -53,10 +53,15 @@ defmodule Aprsme.DeviceCache do
@impl true
def init(_) do
# Load devices on startup
load_devices_into_cache()
case load_devices_into_cache() do
:ok ->
# Schedule periodic refresh
Process.send_after(self(), :refresh_cache, @refresh_interval)
# Schedule periodic refresh
Process.send_after(self(), :refresh_cache, @refresh_interval)
:error ->
# If initial load failed, retry sooner
Process.send_after(self(), :refresh_cache, 5_000)
end
{:ok, %{}}
end
@ -86,12 +91,23 @@ defmodule Aprsme.DeviceCache do
# Private functions
defp load_devices_into_cache do
devices = Repo.all(Devices)
require Logger
# Store all devices in cache
case Cachex.put(@cache_name, :all_devices, devices) do
{:ok, true} -> :ok
error -> error
try do
devices = Repo.all(Devices)
# Store all devices in cache
case Cachex.put(@cache_name, :all_devices, devices) do
{:ok, true} -> :ok
error -> error
end
rescue
error in [Postgrex.Error, DBConnection.ConnectionError] ->
# Handle case where database or table doesn't exist yet
Logger.warning("Failed to load devices: #{inspect(error)}. Will retry later.")
# Store empty list for now
Cachex.put(@cache_name, :all_devices, [])
:error
end
end

View file

@ -13,10 +13,29 @@ defmodule Aprsme.Release do
# Gettext translations are automatically compiled during Mix compilation
# Create database if it doesn't exist
create_database()
# Run migrations
{:ok, _, _} = Ecto.Migrator.with_repo(Aprsme.Repo, &Ecto.Migrator.run(&1, :up, all: true))
end
defp create_database do
require Logger
case Aprsme.Repo.__adapter__().storage_up(Aprsme.Repo.config()) do
:ok ->
Logger.info("Database created successfully")
{:error, :already_up} ->
Logger.info("Database already exists")
{:error, error} ->
Logger.error("Failed to create database: #{inspect(error)}")
raise "Database creation failed: #{inspect(error)}"
end
end
def rollback(repo, version) do
load_app()
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))