db

package
v1.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllIngredientNames

func AllIngredientNames(db *DB) ([]string, error)

AllIngredientNames returns every ingredient name in alphabetical order.

func AllTagsByContext

func AllTagsByContext(db *DB, context string) ([]string, error)

AllTagsByContext returns every tag value for a given context (for filter menus).

func AllUnits

func AllUnits(db *DB) ([]string, error)

AllUnits returns every distinct unit used in recipe ingredients, alphabetically.

func AttachTag

func AttachTag(db *DB, recipeID, tagID int64) error

AttachTag links a tag to a recipe (idempotent).

func BackfillIngredientTypes

func BackfillIngredientTypes(sqlDB *DB) error

BackfillIngredientTypes migrates ingredient_type values to the five-type scheme introduced alongside baker's-percentage rework:

  • "dry" ingredients whose names match flour patterns → "flour"
  • "wet" ingredients whose names match fat patterns → "fat"

All other existing type values are left unchanged. Safe to call at every startup: rows that already carry the correct type are not touched.

func BackfillQuantityNumeric

func BackfillQuantityNumeric(sqlDB *DB) error

BackfillQuantityNumeric populates quantity_numeric for any recipe_ingredients rows where it is NULL and quantity is non-empty. Safe to call at every startup: it is a no-op once all rows are populated. Uses a single transaction with a prepared statement so the entire backfill is one atomic disk write.

func BackupSQLite

func BackupSQLite(srcPath, destPath string, logger *slog.Logger) error

BackupSQLite copies the SQLite database file at srcPath to destPath.

func ClearSQLiteData

func ClearSQLiteData(sqlite *DB, logger *slog.Logger) error

ClearSQLiteData deletes all recipe data from the sqlite DB in reverse foreign-key order. The schema and file are preserved; only data is removed. Call this only after MigrateToPostgres has completed successfully.

func CompleteAIRun

func CompleteAIRun(db *DB, id int64, rawResponse string) error

CompleteAIRun marks an existing run as succeeded.

func CreateAIRun

func CreateAIRun(db *DB, run *models.AIClassifierRun) (int64, error)

CreateAIRun inserts a new (in-progress) AI run record and returns its ID.

func CreateRecipe

func CreateRecipe(db *DB, r *models.Recipe) (int64, error)

CreateRecipe inserts a new recipe and returns its ID.

func DeleteAIRun

func DeleteAIRun(db *DB, id int64) error

DeleteAIRun removes a single AI run by ID.

func DeleteAIRunsOlderThan

func DeleteAIRunsOlderThan(db *DB, age time.Duration) (int64, error)

DeleteAIRunsOlderThan removes AI runs created before now-age and returns the count deleted.

func DeleteRecipe

func DeleteRecipe(db *DB, id int64) error

DeleteRecipe permanently removes a recipe. Related rows in recipe_ingredients and recipe_tags are removed automatically via ON DELETE CASCADE.

func DeleteRecipeIngredients

func DeleteRecipeIngredients(db *DB, recipeID int64) error

DeleteRecipeIngredients removes all ingredient lines for a recipe.

func DeleteRecipeTags

func DeleteRecipeTags(db *DB, recipeID int64) error

DeleteRecipeTags removes all tags for a recipe.

func DeleteTag

func DeleteTag(db *DB, id int64) error

DeleteTag removes a tag row; recipe_tags cascade-deletes automatically.

func FailAIRun

func FailAIRun(db *DB, id int64, errClass, errMsg string) error

FailAIRun marks an existing run as failed with error details.

func FindOrCreateIngredient

func FindOrCreateIngredient(db *DB, name string) (int64, error)

FindOrCreateIngredient returns the existing ingredient ID or creates a new one.

func FindOrCreateTag

func FindOrCreateTag(db *DB, name, context string) (int64, error)

FindOrCreateTag returns the existing tag ID or creates a new one.

func GetAIRun

func GetAIRun(db *DB, id int64) (*models.AIClassifierRun, error)

GetAIRun returns the full AIClassifierRun record by ID.

func GetRecipe

func GetRecipe(db *DB, id int64) (*models.Recipe, error)

GetRecipe retrieves a recipe by ID with all associations loaded.

func GetRecipeByURL

func GetRecipeByURL(sqlDB *DB, url string) (*models.Recipe, error)

GetRecipeByURL returns the recipe whose source_url matches url (case-insensitively), or nil if no such recipe exists.

func GetRecipeIngredients

func GetRecipeIngredients(db *DB, recipeID int64) ([]models.RecipeIngredient, error)

GetRecipeIngredients loads all ingredient lines for a recipe, ordered by section then position.

func GetRecipeTags

func GetRecipeTags(db *DB, recipeID int64) ([]models.Tag, error)

GetRecipeTags loads all tags for a recipe.

func GetRecipesByIDs added in v1.7.0

func GetRecipesByIDs(db *DB, ids []int64) ([]models.Recipe, error)

GetRecipesByIDs returns fully-hydrated recipes for the given IDs, newest first.

func InsertRecipeIngredient

func InsertRecipeIngredient(db *DB, ri *models.RecipeIngredient) error

InsertRecipeIngredient adds one ingredient line to a recipe.

func ListRecipes

func ListRecipes(db *DB, f RecipeFilter) ([]models.Recipe, error)

ListRecipes returns recipes matching the filter, newest first.

func MergeIngredient

func MergeIngredient(db *DB, sourceID, targetID int64) error

MergeIngredient repoints all recipe_ingredient rows from source to target, then deletes the source ingredient.

func MergeTag

func MergeTag(db *DB, sourceID, targetID int64) error

MergeTag repoints all recipe_tags from sourceID to targetID, then deletes the source tag.

func MergeUnit

func MergeUnit(db *DB, sourceName, targetName string) error

MergeUnit is equivalent to RenameUnit — all rows with sourceName get targetName.

func RecipeCount

func RecipeCount(db *DB) (int, error)

RecipeCount returns the number of recipes in the database. Used to decide whether to offer migration.

func RenameIngredient

func RenameIngredient(db *DB, id int64, newName string) error

RenameIngredient updates an ingredient's name.

func RenameTag

func RenameTag(db *DB, id int64, newName string) error

RenameTag updates a tag's name in-place.

func RenameUnit

func RenameUnit(db *DB, oldName, newName string) error

RenameUnit updates every recipe_ingredient row with oldName to newName.

func SQLiteHasRecipes

func SQLiteHasRecipes(dbPath string) (int, error)

SQLiteHasRecipes reports whether the SQLite DB at dbPath exists and contains at least one recipe. Returns (0, nil) when the file does not exist.

func SaveRecipe

func SaveRecipe(db *DB, r *models.Recipe, tagNames map[string][]string) error

SaveRecipe creates (r.ID==0) or updates (r.ID>0) a recipe with its tags and ingredients. r.Ingredients[*].IngredientName must be set; IDs are ignored. The entire operation runs in a transaction so partial failures are rolled back.

func SetIngredientType

func SetIngredientType(db *DB, ingredientID int64, ingredientType string) error

SetIngredientType updates the ingredient_type field on the canonical ingredients table. Called after AI extraction to persist classification.

func TestPostgresConnection

func TestPostgresConnection(dsn string) error

TestPostgresConnection attempts to open and ping a postgres connection with a 5-second timeout. Used for config-time validation.

func UpdateRecipeFields

func UpdateRecipeFields(db *DB, r *models.Recipe) error

UpdateRecipeFields applies extracted AI data to an existing recipe.

func UpdateRecipeNotes

func UpdateRecipeNotes(db *DB, id int64, notes string) error

UpdateRecipeNotes saves the freeform notes text for a recipe.

func UpdateRecipeRating

func UpdateRecipeRating(db *DB, id int64, rating *int) error

UpdateRecipeRating sets or clears the rating (1–5) for a recipe. Pass nil to clear the rating.

func UpdateRecipeStatus

func UpdateRecipeStatus(db *DB, id int64, status string) error

UpdateRecipeStatus changes only the status and updated_at fields.

Types

type AIRunSummary

type AIRunSummary struct {
	ID           int64      `db:"id"`
	RecipeName   string     `db:"recipe_name"` // "" when recipe has been deleted
	ServiceClass string     `db:"service_class"`
	AIModel      string     `db:"ai_model"`
	Success      bool       `db:"success"`
	DurationMS   int64      // computed after scan
	StartedAt    *time.Time `db:"started_at"`
	CompletedAt  *time.Time `db:"completed_at"`
	CreatedAt    time.Time  `db:"created_at"`
}

AIRunSummary is a lightweight view of an ai_classifier_runs row.

func ListAIRunSummaries

func ListAIRunSummaries(db *DB) ([]AIRunSummary, error)

ListAIRunSummaries returns all AI runs, newest first, with recipe name when available.

type DB

type DB struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

DB wraps *sqlx.DB and automatically rebinds ? placeholders to the driver's native syntax (? for SQLite, $1/$2/… for PostgreSQL).

func Open

func Open(cfg *config.Config, logger goose.Logger) (*DB, error)

Open opens the database specified by cfg, runs all pending migrations, and returns a ready-to-use *DB. For SQLite it creates the directory if needed. For PostgreSQL it connects using cfg.PostgresDSN.

Returns an error if the connection or migrations fail. PostgreSQL connection failures are fatal — they are not silently downgraded to SQLite.

func OpenMemory

func OpenMemory() (*DB, error)

OpenMemory opens an in-memory SQLite database for testing.

func OpenSQLite

func OpenSQLite(dbPath string, logger goose.Logger) (*DB, error)

OpenSQLite opens (or creates) a SQLite database at dbPath.

func (*DB) Driver

func (d *DB) Driver() string

Driver returns "postgres" or "sqlite3".

func (*DB) Exec

func (d *DB) Exec(query string, args ...interface{}) (sql.Result, error)

Exec rebinds the query then delegates to sqlx.DB.Exec.

func (*DB) Get

func (d *DB) Get(dest interface{}, query string, args ...interface{}) error

Get rebinds the query then delegates to sqlx.DB.Get.

func (*DB) QueryRow

func (d *DB) QueryRow(query string, args ...interface{}) *sql.Row

QueryRow rebinds the query then delegates to sqlx.DB.QueryRow.

func (*DB) Select

func (d *DB) Select(dest interface{}, query string, args ...interface{}) error

Select rebinds the query then delegates to sqlx.DB.Select.

type IngredientWithCount

type IngredientWithCount struct {
	ID    int64  `db:"id"`
	Name  string `db:"name"`
	Count int    `db:"count"`
}

IngredientWithCount is an ingredient augmented with the number of recipe_ingredient rows.

func ListIngredientsWithCount

func ListIngredientsWithCount(db *DB, search string) ([]IngredientWithCount, error)

ListIngredientsWithCount returns ingredients with their usage counts, sorted alphabetically. When search is non-empty, only ingredients whose name contains the search string (case-insensitive) are returned.

type MigrationResult

type MigrationResult struct {
	Imported int
	Skipped  int
}

MigrationResult holds counts from a completed migration.

func MigrateToPostgres

func MigrateToPostgres(sqlite *DB, pg *DB, logger *slog.Logger) (MigrationResult, error)

MigrateToPostgres copies recipes from sqlite to pg using the same find-or-create paths as normal recipe saves. Recipes with a source_url that already exists in pg are skipped to avoid duplicates. Manual recipes (no source_url) are always imported.

AI classifier runs are copied with remapped recipe IDs. The sqlite DB is NOT modified by this function — call ClearSQLiteData after confirming success.

type RecipeFilter

type RecipeFilter struct {
	Query               string // name or ingredient substring
	Courses             []string
	CookingMethods      []string
	CulturalInfluences  []string
	DietaryRestrictions []string
	StatusFilter        string // empty = all statuses
	IsBread             bool   // false = all recipes; true = bread/dough only
	MinRating           int    // 0 = any; 1–5 = minimum rating (NULL ratings excluded)
}

RecipeFilter holds search/filter parameters for listing recipes.

type TagWithCount

type TagWithCount struct {
	ID      int64  `db:"id"`
	Name    string `db:"name"`
	Context string `db:"context"`
	Count   int    `db:"count"`
}

TagWithCount is a tag row augmented with the number of recipes using it.

func ListTagsByContext

func ListTagsByContext(db *DB, context string) ([]TagWithCount, error)

ListTagsByContext returns all tags in a context with their recipe counts, sorted by name.

type UnitWithCount

type UnitWithCount struct {
	Name  string `db:"name"`
	Count int    `db:"count"`
}

UnitWithCount is a distinct unit value with its usage count.

func ListUnitsWithCount

func ListUnitsWithCount(db *DB) ([]UnitWithCount, error)

ListUnitsWithCount returns all distinct non-empty unit values with usage counts.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL