Initial working version
This commit is contained in:
commit
3d7c232b94
32 files changed
+4743
No files matched your search
@@ -0,0 +1,77 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
//go:embed schema.sql
|
||||
var schemaSQL string
|
||||
|
||||
type DB struct {
|
||||
Conn *sql.DB
|
||||
}
|
||||
|
||||
func Open(path string) (*DB, error) {
|
||||
// Ensure parent directory exists
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("creating db directory: %w", err)
|
||||
}
|
||||
|
||||
// Open CGO-free SQLite connection with high-concurrency WAL mode and busy timeout
|
||||
conn, err := sql.Open("sqlite", path+"?_journal_mode=WAL&_busy_timeout=5000&_fk=true")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opening database: %w", err)
|
||||
}
|
||||
|
||||
// SQLite operates best in Go with max open connections limited to 1, avoiding concurrent write lockouts
|
||||
conn.SetMaxOpenConns(1)
|
||||
|
||||
if err := migrate(conn); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &DB{Conn: conn}, nil
|
||||
}
|
||||
|
||||
func migrate(conn *sql.DB) error {
|
||||
// Execute schema migrations
|
||||
_, err := conn.Exec(schemaSQL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("running schema migrations: %w", err)
|
||||
}
|
||||
|
||||
// Check if locations count is 0
|
||||
var count int
|
||||
err = conn.QueryRow("SELECT COUNT(*) FROM locations").Scan(&count)
|
||||
if err != nil {
|
||||
return fmt.Errorf("checking locations count: %w", err)
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
// Create the default room with explicit ID 1
|
||||
_, err = conn.Exec("INSERT INTO locations (id, name, description) VALUES (1, 'Default Room', 'Default Room for unassigned items')")
|
||||
if err != nil {
|
||||
return fmt.Errorf("inserting default room: %w", err)
|
||||
}
|
||||
|
||||
// Create the corresponding tag for Default Room
|
||||
_, err = conn.Exec("INSERT INTO tags (name, color, description) VALUES ('Default Room', '#f59e0b', 'Default tag for items in Default Room')")
|
||||
if err != nil {
|
||||
return fmt.Errorf("inserting default room tag: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) Close() error {
|
||||
return d.Conn.Close()
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Item struct {
|
||||
ID int64
|
||||
Name string
|
||||
Description string
|
||||
Quantity int
|
||||
ModelNumber string
|
||||
SerialNumber string
|
||||
Status string // 'In Use', 'In Storage', 'Borrowed', 'Lost', 'Disposed'
|
||||
LocationID sql.NullInt64
|
||||
LocationName sql.NullString
|
||||
PurchasePrice sql.NullFloat64
|
||||
PurchaseDate sql.NullString // ISO8601 YYYY-MM-DD
|
||||
WarrantyMonths sql.NullInt64
|
||||
Supplier string
|
||||
CustomFields string // JSON text
|
||||
ImagePath string
|
||||
ReceiptPath string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Tags []Tag // Loaded on demand
|
||||
ShortSlug string // Generated or loaded short URL slug
|
||||
}
|
||||
|
||||
func (d *DB) CreateItem(item *Item, tagIDs []int64) (*Item, error) {
|
||||
// Wrap in a SQLite transaction for safe consistency
|
||||
tx, err := d.Conn.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
res, err := tx.Exec(`
|
||||
INSERT INTO items (
|
||||
name, description, quantity, model_number, serial_number, status,
|
||||
location_id, purchase_price, purchase_date, warranty_months, supplier,
|
||||
custom_fields, image_path, receipt_path
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
item.Name, item.Description, item.Quantity, item.ModelNumber, item.SerialNumber, item.Status,
|
||||
item.LocationID, item.PurchasePrice, item.PurchaseDate, item.WarrantyMonths, item.Supplier,
|
||||
item.CustomFields, item.ImagePath, item.ReceiptPath,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
itemID, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.ID = itemID
|
||||
|
||||
// Insert tag associations
|
||||
if len(tagIDs) > 0 {
|
||||
stmt, err := tx.Prepare("INSERT INTO item_tags (item_id, tag_id) VALUES (?, ?)")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
for _, tagID := range tagIDs {
|
||||
_, err = stmt.Exec(item.ID, tagID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (d *DB) GetItem(id int64) (*Item, error) {
|
||||
row := d.Conn.QueryRow(`
|
||||
SELECT
|
||||
i.id, i.name, i.description, i.quantity, i.model_number, i.serial_number, i.status,
|
||||
i.location_id, l.name AS location_name, i.purchase_price, i.purchase_date, i.warranty_months,
|
||||
i.supplier, i.custom_fields, i.image_path, i.receipt_path, i.created_at, i.updated_at,
|
||||
COALESCE(lk.slug, '') AS short_slug
|
||||
FROM items i
|
||||
LEFT JOIN locations l ON i.location_id = l.id
|
||||
LEFT JOIN links lk ON lk.item_id = i.id
|
||||
WHERE i.id = ?`,
|
||||
id,
|
||||
)
|
||||
|
||||
item, err := scanItem(row)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Load tags for this item
|
||||
tags, err := d.getItemTags(item.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.Tags = d.arrangeTags(item.LocationName.String, tags)
|
||||
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (d *DB) UpdateItem(item *Item, tagIDs []int64) error {
|
||||
tx, err := d.Conn.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
_, err = tx.Exec(`
|
||||
UPDATE items SET
|
||||
name = ?, description = ?, quantity = ?, model_number = ?, serial_number = ?, status = ?,
|
||||
location_id = ?, purchase_price = ?, purchase_date = ?, warranty_months = ?, supplier = ?,
|
||||
custom_fields = ?, image_path = ?, receipt_path = ?, updated_at = datetime('now')
|
||||
WHERE id = ?`,
|
||||
item.Name, item.Description, item.Quantity, item.ModelNumber, item.SerialNumber, item.Status,
|
||||
item.LocationID, item.PurchasePrice, item.PurchaseDate, item.WarrantyMonths, item.Supplier,
|
||||
item.CustomFields, item.ImagePath, item.ReceiptPath, item.ID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Rebuild tag associations
|
||||
_, err = tx.Exec("DELETE FROM item_tags WHERE item_id = ?", item.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(tagIDs) > 0 {
|
||||
stmt, err := tx.Prepare("INSERT INTO item_tags (item_id, tag_id) VALUES (?, ?)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
for _, tagID := range tagIDs {
|
||||
_, err = stmt.Exec(item.ID, tagID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (d *DB) DeleteItem(id int64) error {
|
||||
// Schema cascading rules handle tag mappings and short links automatically
|
||||
_, err := d.Conn.Exec("DELETE FROM items WHERE id = ?", id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) ListItems() ([]Item, error) {
|
||||
rows, err := d.Conn.Query(`
|
||||
SELECT
|
||||
i.id, i.name, i.description, i.quantity, i.model_number, i.serial_number, i.status,
|
||||
i.location_id, l.name AS location_name, i.purchase_price, i.purchase_date, i.warranty_months,
|
||||
i.supplier, i.custom_fields, i.image_path, i.receipt_path, i.created_at, i.updated_at,
|
||||
COALESCE(lk.slug, '') AS short_slug
|
||||
FROM items i
|
||||
LEFT JOIN locations l ON i.location_id = l.id
|
||||
LEFT JOIN links lk ON lk.item_id = i.id
|
||||
ORDER BY i.id DESC`,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []Item
|
||||
var itemIDs []int64
|
||||
for rows.Next() {
|
||||
var i Item
|
||||
var created, updated string
|
||||
var locID sql.NullInt64
|
||||
var locName sql.NullString
|
||||
var price sql.NullFloat64
|
||||
var date sql.NullString
|
||||
var warranty sql.NullInt64
|
||||
|
||||
err := rows.Scan(
|
||||
&i.ID, &i.Name, &i.Description, &i.Quantity, &i.ModelNumber, &i.SerialNumber, &i.Status,
|
||||
&locID, &locName, &price, &date, &warranty, &i.Supplier, &i.CustomFields, &i.ImagePath,
|
||||
&i.ReceiptPath, &created, &updated, &i.ShortSlug,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
i.LocationID = locID
|
||||
i.LocationName = locName
|
||||
i.PurchasePrice = price
|
||||
i.PurchaseDate = date
|
||||
i.WarrantyMonths = warranty
|
||||
i.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created)
|
||||
i.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated)
|
||||
|
||||
items = append(items, i)
|
||||
itemIDs = append(itemIDs, i.ID)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// Bulk load tags to avoid N+1 queries
|
||||
tagMap, err := d.getBulkItemTags(itemIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Map tags to items
|
||||
for idx, item := range items {
|
||||
locName := ""
|
||||
if item.LocationName.Valid {
|
||||
locName = item.LocationName.String
|
||||
}
|
||||
if tags, exists := tagMap[item.ID]; exists {
|
||||
items[idx].Tags = d.arrangeTags(locName, tags)
|
||||
} else {
|
||||
items[idx].Tags = d.arrangeTags(locName, []Tag{})
|
||||
}
|
||||
}
|
||||
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (d *DB) getItemTags(itemID int64) ([]Tag, error) {
|
||||
rows, err := d.Conn.Query(`
|
||||
SELECT t.id, t.name, t.color, t.description
|
||||
FROM item_tags it
|
||||
JOIN tags t ON it.tag_id = t.id
|
||||
WHERE it.item_id = ?`,
|
||||
itemID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var tags []Tag
|
||||
for rows.Next() {
|
||||
var t Tag
|
||||
if err := rows.Scan(&t.ID, &t.Name, &t.Color, &t.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tags = append(tags, t)
|
||||
}
|
||||
return tags, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) getBulkItemTags(itemIDs []int64) (map[int64][]Tag, error) {
|
||||
tagMap := make(map[int64][]Tag)
|
||||
if len(itemIDs) == 0 {
|
||||
return tagMap, nil
|
||||
}
|
||||
|
||||
// Dynamic IN clause building for pure SQL safely (itemIDs are system-generated int64 values)
|
||||
inClause := ""
|
||||
for i, id := range itemIDs {
|
||||
if i > 0 {
|
||||
inClause += ","
|
||||
}
|
||||
inClause += fmt.Sprintf("%d", id)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT it.item_id, t.id, t.name, t.color, t.description
|
||||
FROM item_tags it
|
||||
JOIN tags t ON it.tag_id = t.id
|
||||
WHERE it.item_id IN (%s)`, inClause)
|
||||
|
||||
rows, err := d.Conn.Query(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var itemID int64
|
||||
var t Tag
|
||||
if err := rows.Scan(&itemID, &t.ID, &t.Name, &t.Color, &t.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tagMap[itemID] = append(tagMap[itemID], t)
|
||||
}
|
||||
|
||||
return tagMap, rows.Err()
|
||||
}
|
||||
|
||||
func scanItem(row interface {
|
||||
Scan(dest ...any) error
|
||||
}) (*Item, error) {
|
||||
var i Item
|
||||
var created, updated string
|
||||
var locID sql.NullInt64
|
||||
var locName sql.NullString
|
||||
var price sql.NullFloat64
|
||||
var date sql.NullString
|
||||
var warranty sql.NullInt64
|
||||
|
||||
err := row.Scan(
|
||||
&i.ID, &i.Name, &i.Description, &i.Quantity, &i.ModelNumber, &i.SerialNumber, &i.Status,
|
||||
&locID, &locName, &price, &date, &warranty, &i.Supplier, &i.CustomFields, &i.ImagePath,
|
||||
&i.ReceiptPath, &created, &updated, &i.ShortSlug,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
i.LocationID = locID
|
||||
i.LocationName = locName
|
||||
i.PurchasePrice = price
|
||||
i.PurchaseDate = date
|
||||
i.WarrantyMonths = warranty
|
||||
i.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created)
|
||||
i.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated)
|
||||
|
||||
return &i, nil
|
||||
}
|
||||
|
||||
func (d *DB) arrangeTags(roomName string, tags []Tag) []Tag {
|
||||
if roomName == "" {
|
||||
return tags
|
||||
}
|
||||
|
||||
var roomTag *Tag
|
||||
var otherTags []Tag
|
||||
|
||||
for i, t := range tags {
|
||||
if t.Name == roomName {
|
||||
roomTag = &tags[i]
|
||||
} else {
|
||||
otherTags = append(otherTags, t)
|
||||
}
|
||||
}
|
||||
|
||||
if roomTag == nil {
|
||||
// Room tag was not in the loaded tags, let's fetch it from db
|
||||
row := d.Conn.QueryRow("SELECT id, name, color, description FROM tags WHERE name = ?", roomName)
|
||||
var t Tag
|
||||
if err := row.Scan(&t.ID, &t.Name, &t.Color, &t.Description); err == nil {
|
||||
roomTag = &t
|
||||
} else {
|
||||
// fallback: construct a temporary Tag
|
||||
roomTag = &Tag{
|
||||
Name: roomName,
|
||||
Color: "#f59e0b",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prepend roomTag
|
||||
return append([]Tag{*roomTag}, otherTags...)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Link struct {
|
||||
ID int64
|
||||
Slug string
|
||||
URL string
|
||||
ItemID sql.NullInt64
|
||||
CreatedBy string
|
||||
Clicks int64
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (d *DB) CreateLink(slug, url, createdBy string, itemID sql.NullInt64) (*Link, error) {
|
||||
res, err := d.Conn.Exec(
|
||||
"INSERT INTO links (slug, url, created_by, item_id) VALUES (?, ?, ?, ?)",
|
||||
slug, url, createdBy, itemID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return &Link{
|
||||
ID: id,
|
||||
Slug: slug,
|
||||
URL: url,
|
||||
ItemID: itemID,
|
||||
CreatedBy: createdBy,
|
||||
CreatedAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *DB) GetLinkBySlug(slug string) (*Link, error) {
|
||||
row := d.Conn.QueryRow("SELECT id, slug, url, item_id, created_by, clicks, created_at FROM links WHERE slug = ?", slug)
|
||||
return scanLink(row)
|
||||
}
|
||||
|
||||
func (d *DB) GetLinkByItemID(itemID int64) (*Link, error) {
|
||||
row := d.Conn.QueryRow("SELECT id, slug, url, item_id, created_by, clicks, created_at FROM links WHERE item_id = ?", itemID)
|
||||
return scanLink(row)
|
||||
}
|
||||
|
||||
func (d *DB) IncrementLinkClicks(slug string) error {
|
||||
_, err := d.Conn.Exec("UPDATE links SET clicks = clicks + 1 WHERE slug = ?", slug)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) ListLinks() ([]Link, error) {
|
||||
rows, err := d.Conn.Query("SELECT id, slug, url, item_id, created_by, clicks, created_at FROM links ORDER BY id DESC")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var links []Link
|
||||
for rows.Next() {
|
||||
var l Link
|
||||
var itemID sql.NullInt64
|
||||
var ts string
|
||||
if err := rows.Scan(&l.ID, &l.Slug, &l.URL, &itemID, &l.CreatedBy, &l.Clicks, &ts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.ItemID = itemID
|
||||
l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", ts)
|
||||
links = append(links, l)
|
||||
}
|
||||
return links, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) DeleteLink(id int64) error {
|
||||
_, err := d.Conn.Exec("DELETE FROM links WHERE id = ?", id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) UpdateLink(id int64, slug, url string) error {
|
||||
_, err := d.Conn.Exec("UPDATE links SET slug = ?, url = ? WHERE id = ?", slug, url, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) SlugExists(slug string) (bool, error) {
|
||||
var count int
|
||||
err := d.Conn.QueryRow("SELECT COUNT(*) FROM links WHERE slug = ?", slug).Scan(&count)
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func scanLink(row interface {
|
||||
Scan(dest ...any) error
|
||||
}) (*Link, error) {
|
||||
var l Link
|
||||
var itemID sql.NullInt64
|
||||
var ts string
|
||||
if err := row.Scan(&l.ID, &l.Slug, &l.URL, &itemID, &l.CreatedBy, &l.Clicks, &ts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.ItemID = itemID
|
||||
l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", ts)
|
||||
return &l, nil
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Location struct {
|
||||
ID int64
|
||||
Name string
|
||||
Description string
|
||||
ParentID sql.NullInt64
|
||||
ParentName sql.NullString // Resolved parent location name
|
||||
ImagePath string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func (d *DB) CreateLocation(name, description string, parentID sql.NullInt64, imagePath string) (*Location, error) {
|
||||
tx, err := d.Conn.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
res, err := tx.Exec(
|
||||
"INSERT INTO locations (name, description, parent_id, image_path) VALUES (?, ?, ?, ?)",
|
||||
name, description, parentID, imagePath,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
|
||||
// Automatically create a corresponding tag for the new location if it doesn't exist
|
||||
var tagID int64
|
||||
err = tx.QueryRow("SELECT id FROM tags WHERE name = ?", name).Scan(&tagID)
|
||||
if err != nil {
|
||||
_, err = tx.Exec(
|
||||
"INSERT INTO tags (name, color, description) VALUES (?, '#f59e0b', ?)",
|
||||
name, "Tag representing location: "+name,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Location{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Description: description,
|
||||
ParentID: parentID,
|
||||
ImagePath: imagePath,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *DB) GetLocation(id int64) (*Location, error) {
|
||||
row := d.Conn.QueryRow(`
|
||||
SELECT l.id, l.name, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.created_at, l.updated_at
|
||||
FROM locations l
|
||||
LEFT JOIN locations p ON l.parent_id = p.id
|
||||
WHERE l.id = ?`,
|
||||
id,
|
||||
)
|
||||
return scanLocation(row)
|
||||
}
|
||||
|
||||
func (d *DB) UpdateLocation(id int64, name, description string, parentID sql.NullInt64, imagePath string) error {
|
||||
if id == 1 && name != "Default Room" {
|
||||
return fmt.Errorf("cannot rename the Default Room")
|
||||
}
|
||||
|
||||
tx, err := d.Conn.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var oldName string
|
||||
err = tx.QueryRow("SELECT name FROM locations WHERE id = ?", id).Scan(&oldName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(
|
||||
"UPDATE locations SET name = ?, description = ?, parent_id = ?, image_path = ?, updated_at = datetime('now') WHERE id = ?",
|
||||
name, description, parentID, imagePath, id,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Update the tag name as well
|
||||
_, _ = tx.Exec("UPDATE tags SET name = ? WHERE name = ?", name, oldName)
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (d *DB) DeleteLocation(id int64) error {
|
||||
if id == 1 {
|
||||
return fmt.Errorf("cannot delete the Default Room")
|
||||
}
|
||||
|
||||
tx, err := d.Conn.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Get location name to delete the tag as well
|
||||
var name string
|
||||
err = tx.QueryRow("SELECT name FROM locations WHERE id = ?", id).Scan(&name)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil // already deleted
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Move items in this location to Default Room (ID = 1)
|
||||
_, err = tx.Exec("UPDATE items SET location_id = 1 WHERE location_id = ?", id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Get the Default Room tag ID
|
||||
var defaultTagID int64
|
||||
_ = tx.QueryRow("SELECT id FROM tags WHERE name = 'Default Room'").Scan(&defaultTagID)
|
||||
|
||||
if defaultTagID > 0 {
|
||||
// Fetch all items that were just moved to Default Room (ID = 1) and insert Default Room tag reference
|
||||
rows, err := tx.Query("SELECT id FROM items WHERE location_id = 1")
|
||||
if err == nil {
|
||||
var movedItemIDs []int64
|
||||
for rows.Next() {
|
||||
var mid int64
|
||||
if err := rows.Scan(&mid); err == nil {
|
||||
movedItemIDs = append(movedItemIDs, mid)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
for _, mid := range movedItemIDs {
|
||||
_, _ = tx.Exec("INSERT OR IGNORE INTO item_tags (item_id, tag_id) VALUES (?, ?)", mid, defaultTagID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete the tag representing this location
|
||||
var tagID int64
|
||||
err = tx.QueryRow("SELECT id FROM tags WHERE name = ?", name).Scan(&tagID)
|
||||
if err == nil && name != "Default Room" {
|
||||
_, _ = tx.Exec("DELETE FROM tags WHERE id = ?", tagID)
|
||||
}
|
||||
|
||||
// Set parent references to NULL
|
||||
_, err = tx.Exec("UPDATE locations SET parent_id = NULL WHERE parent_id = ?", id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete the location
|
||||
_, err = tx.Exec("DELETE FROM locations WHERE id = ?", id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (d *DB) ListLocations() ([]Location, error) {
|
||||
rows, err := d.Conn.Query(`
|
||||
SELECT l.id, l.name, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.created_at, l.updated_at
|
||||
FROM locations l
|
||||
LEFT JOIN locations p ON l.parent_id = p.id
|
||||
ORDER BY l.name ASC`,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var locations []Location
|
||||
for rows.Next() {
|
||||
var l Location
|
||||
var parentID sql.NullInt64
|
||||
var parentName sql.NullString
|
||||
var created, updated string
|
||||
if err := rows.Scan(&l.ID, &l.Name, &l.Description, &parentID, &parentName, &l.ImagePath, &created, &updated); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.ParentID = parentID
|
||||
l.ParentName = parentName
|
||||
l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created)
|
||||
l.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated)
|
||||
locations = append(locations, l)
|
||||
}
|
||||
return locations, rows.Err()
|
||||
}
|
||||
|
||||
func scanLocation(row interface {
|
||||
Scan(dest ...any) error
|
||||
}) (*Location, error) {
|
||||
var l Location
|
||||
var parentID sql.NullInt64
|
||||
var parentName sql.NullString
|
||||
var created, updated string
|
||||
if err := row.Scan(&l.ID, &l.Name, &l.Description, &parentID, &parentName, &l.ImagePath, &created, &updated); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.ParentID = parentID
|
||||
l.ParentName = parentName
|
||||
l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created)
|
||||
l.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated)
|
||||
return &l, nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
-- SQLite Database Schema for Solis
|
||||
-- Enables high-fidelity asset tracking and custom URL shortening
|
||||
|
||||
-- 1. Locations Table (Supports hierarchical locations via parent_id)
|
||||
CREATE TABLE IF NOT EXISTS locations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
parent_id INTEGER REFERENCES locations(id) ON DELETE SET NULL,
|
||||
image_path TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_locations_parent ON locations(parent_id);
|
||||
|
||||
-- 2. Tags Table (Sleek labels for grouping items)
|
||||
CREATE TABLE IF NOT EXISTS tags (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
color TEXT NOT NULL DEFAULT '#e2e8f0', -- Hex code for pill color
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
-- 3. Items Table (Asset entries with purchase records and JSON custom fields)
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
quantity INTEGER NOT NULL DEFAULT 1,
|
||||
model_number TEXT NOT NULL DEFAULT '',
|
||||
serial_number TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'In Use', -- 'In Use', 'In Storage', 'Borrowed', 'Lost', 'Disposed'
|
||||
location_id INTEGER REFERENCES locations(id) ON DELETE SET NULL,
|
||||
purchase_price REAL, -- Double/Real for financial values
|
||||
purchase_date TEXT, -- ISO8601 date string (YYYY-MM-DD)
|
||||
warranty_months INTEGER,
|
||||
supplier TEXT NOT NULL DEFAULT '',
|
||||
custom_fields TEXT NOT NULL DEFAULT '{}', -- JSON text field containing arbitrary key-value custom metadata
|
||||
image_path TEXT NOT NULL DEFAULT '',
|
||||
receipt_path TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_items_location ON items(location_id);
|
||||
|
||||
-- 4. Item Tags Junction Table (Many-to-Many relationship)
|
||||
CREATE TABLE IF NOT EXISTS item_tags (
|
||||
item_id INTEGER NOT NULL REFERENCES items(id) ON DELETE CASCADE,
|
||||
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (item_id, tag_id)
|
||||
);
|
||||
|
||||
-- 5. Links Table (Ported and enhanced from Glimmer)
|
||||
CREATE TABLE IF NOT EXISTS links (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
url TEXT NOT NULL, -- Redirect target (internal, e.g., '/items/12', or external)
|
||||
item_id INTEGER REFERENCES items(id) ON DELETE CASCADE, -- Nullable; links specific assets to short URLs
|
||||
created_by TEXT NOT NULL DEFAULT 'admin',
|
||||
clicks INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_links_slug ON links(slug);
|
||||
CREATE INDEX IF NOT EXISTS idx_links_item ON links(item_id);
|
||||
@@ -0,0 +1,107 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Tag struct {
|
||||
ID int64
|
||||
Name string
|
||||
Color string // Hex representation, e.g. "#3b82f6"
|
||||
Description string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (d *DB) CreateTag(name, color, description string) (*Tag, error) {
|
||||
if color == "" {
|
||||
color = "#e2e8f0" // default soft light gray
|
||||
}
|
||||
res, err := d.Conn.Exec(
|
||||
"INSERT INTO tags (name, color, description) VALUES (?, ?, ?)",
|
||||
name, color, description,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return &Tag{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Color: color,
|
||||
Description: description,
|
||||
CreatedAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *DB) GetTag(id int64) (*Tag, error) {
|
||||
row := d.Conn.QueryRow("SELECT id, name, color, description, created_at FROM tags WHERE id = ?", id)
|
||||
return scanTag(row)
|
||||
}
|
||||
|
||||
func (d *DB) GetTagByName(name string) (*Tag, error) {
|
||||
row := d.Conn.QueryRow("SELECT id, name, color, description, created_at FROM tags WHERE name = ?", name)
|
||||
return scanTag(row)
|
||||
}
|
||||
|
||||
func (d *DB) UpdateTag(id int64, name, color, description string) error {
|
||||
if color == "" {
|
||||
color = "#e2e8f0"
|
||||
}
|
||||
|
||||
var oldName string
|
||||
err := d.Conn.QueryRow("SELECT name FROM tags WHERE id = ?", id).Scan(&oldName)
|
||||
if err == nil && oldName == "Default Room" && name != "Default Room" {
|
||||
return fmt.Errorf("cannot rename the Default Room tag")
|
||||
}
|
||||
|
||||
_, err = d.Conn.Exec(
|
||||
"UPDATE tags SET name = ?, color = ?, description = ? WHERE id = ?",
|
||||
name, color, description, id,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) DeleteTag(id int64) error {
|
||||
var name string
|
||||
err := d.Conn.QueryRow("SELECT name FROM tags WHERE id = ?", id).Scan(&name)
|
||||
if err == nil && name == "Default Room" {
|
||||
return fmt.Errorf("cannot delete the Default Room tag")
|
||||
}
|
||||
|
||||
// Foreign key constraints on item_tags handle cascade delete
|
||||
_, err = d.Conn.Exec("DELETE FROM tags WHERE id = ?", id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) ListTags() ([]Tag, error) {
|
||||
rows, err := d.Conn.Query("SELECT id, name, color, description, created_at FROM tags ORDER BY name ASC")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var tags []Tag
|
||||
for rows.Next() {
|
||||
var t Tag
|
||||
var created string
|
||||
if err := rows.Scan(&t.ID, &t.Name, &t.Color, &t.Description, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created)
|
||||
tags = append(tags, t)
|
||||
}
|
||||
return tags, rows.Err()
|
||||
}
|
||||
|
||||
func scanTag(row interface {
|
||||
Scan(dest ...any) error
|
||||
}) (*Tag, error) {
|
||||
var t Tag
|
||||
var created string
|
||||
if err := row.Scan(&t.ID, &t.Name, &t.Color, &t.Description, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created)
|
||||
return &t, nil
|
||||
}
|
||||
Reference in new issue
Block a user