db

package
v0.0.0-...-f8a28ba Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 31 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

Overview

Package db owns Polka's persisted catalog operations and the entity invariants that must hold for every caller. Higher-level workflows, pure format and storage policy, and filesystem or network work belong outside this package.

DB owns a read-only pool and a single-connection writer pool. Writes queue with a maximum wait independent of the caller's operation deadline. ErrWriterTimeout reports that wait expiring, separately from caller cancellation. Read-only opens have no writer and never migrate.

SQL helpers accept context-bound handles: DB.Read(ctx) provides a Queryer and DB.Write(ctx) provides an Execer. Callers must consume or close rows promptly to release connections. Mutations requiring several related statements use DB.Transact; all SQL within its callback, including reads, must use the Tx. Tx implements both interfaces and carries the transaction's context.

Index

Constants

View Source
const (
	AnnotationColorYellow      = "yellow"
	MaxAnnotationQuoteLength   = 32768
	MaxAnnotationContextLength = 500
	MaxAnnotationNoteLength    = 4000
)
View Source
const (
	DeliveryPresetKindle     = "kindle"
	DeliveryPresetPocketBook = "pocketbook"
	DeliveryPresetGeneric    = "generic"

	DeliveryStatusQueued     = "queued"
	DeliveryStatusConverting = "converting"
	DeliveryStatusSending    = "sending"
	DeliveryStatusSent       = "sent"
	DeliveryStatusFailed     = "failed"
)
View Source
const (
	ReadingStatusUnread   = "unread"
	ReadingStatusReading  = "reading"
	ReadingStatusFinished = "finished"
	ReadingStatusDropped  = "dropped"

	// Foliate reports a fraction rather than a semantic "last page" event. Its
	// own UI already treats this bounded tail as complete, so status follows the
	// same threshold instead of demanding a fragile exact 1.0.
	ReaderFinishedProgress = 0.995
)
View Source
const (
	ThemeSystem = "system"
	ThemeLight  = "light"
	ThemeDark   = "dark"
	ThemeSepia  = "sepia"
)
View Source
const (
	ReaderFlowPaginated = "paginated"
	ReaderFlowScrolled  = "scrolled"

	ReaderStyleOriginal = "original"
	ReaderStylePaper    = "paper"
	ReaderStyleCustom   = "custom"

	DefaultReaderFontSize    = 0
	DefaultReaderColumnWidth = 760
	DefaultReaderLineHeight  = 1.72
)
View Source
const (
	RoleAdmin  = "admin"
	RoleMember = "member"
	RoleReader = "reader"
)

Roles are deliberately fixed and ordered, not a configurable permission matrix. admin handles server-level and irreversible operations (users, storage, purge), member curates the shared catalog, reader is a read-only account with personal state. reader is the default for new non-admin accounts; member is a co-librarian and should be granted deliberately.

View Source
const (
	ContentScopeAll     = "all"
	ContentScopeShelves = "shelves"
)

ContentScope is the visibility half of access control (see db/access.go): 'all', or 'shelves' — a reader-only allowlist of assigned scope shelves. A child account is the expected use: reader + shelves.

View Source
const (
	DefaultWriterLeaseTTL = 30 * time.Second
)
View Source
const DeliveryHistoryLimit = 100

DeliveryHistoryLimit caps completed sends per user and delivery list responses.

View Source
const DuplicateReasonTitleAuthor = "title_author"
View Source
const KoboSyncPageLimit = 100
View Source
const ReadingIdleLimit = 5 * time.Minute

Variables

View Source
var (
	ErrAnnotationNotFound = errors.New("annotation not found")
	ErrInvalidAnnotation  = errors.New("invalid annotation")
)
View Source
var (
	ErrDeliveryDeviceNotFound     = errors.New("delivery device not found")
	ErrDeliveryDeviceNameExists   = errors.New("delivery device name already exists")
	ErrDeliveryDeviceNameMissing  = errors.New("delivery device name is required")
	ErrDeliveryDeviceEmailMissing = errors.New("delivery device email is required")
	ErrInvalidDeliveryPreset      = fmt.Errorf("delivery preset must be %s, %s, or %s", DeliveryPresetKindle, DeliveryPresetPocketBook, DeliveryPresetGeneric)
	ErrDeliveryJobNotFound        = errors.New("delivery job not found")
)
View Source
var (
	ErrKoboConnectionNotFound = errors.New("kobo connection not found")
	ErrKoboConnectionExists   = errors.New("kobo connection already exists")
	ErrKoboInvalidCursor      = errors.New("invalid kobo sync cursor")
)
View Source
var (
	ErrAssetNotFound      = errors.New("asset not found")
	ErrInvalidReaderInput = errors.New("invalid reader input")
	ErrReadingConflict    = errors.New("reading data changed on another reader")
)
View Source
var (
	ErrReadingStatusBookMissing     = errors.New("book not found")
	ErrInvalidReadingStatus         = errors.New("invalid reading status")
	ErrReadingStatusUndoUnavailable = errors.New("reading status change cannot be undone")
)
View Source
var (
	ErrShelfNotFound      = errors.New("shelf not found")
	ErrQueryShelf         = errors.New("query shelves do not have explicit membership")
	ErrEmptyShelfName     = errors.New("shelf name must not be empty")
	ErrShelfOwnerRequired = errors.New("shelf owner is required")
	ErrInvalidShelfInput  = errors.New("invalid shelf input")
)
View Source
var (
	ErrInvalidUserSettings = errors.New("invalid user settings")
	ErrInvalidTheme        = errorWithDetail(ErrInvalidUserSettings, "theme must be system, light, dark, or sepia")
	ErrInvalidTimeZone     = errorWithDetail(ErrInvalidUserSettings, "choose a valid named time zone, such as Europe/Berlin or UTC")
)
View Source
var ErrAuthorNotFound = errors.New("no author named")
View Source
var ErrInvalidAppTokenInput = errors.New("invalid app token input")

ErrInvalidAppTokenInput classifies token values that are safe to return as a client error; its concrete error retains the useful validation detail.

View Source
var ErrInvalidDuplicateGroup = errors.New("duplicate group is no longer valid")
View Source
var ErrInvalidLocator = errors.New("invalid locator")
View Source
var ErrInvalidUserInput = errors.New("invalid user input")

ErrInvalidUserInput classifies account values that are safe to return as a client error; its concrete error retains the useful validation detail.

View Source
var ErrKOReaderInvalidInput = errors.New("invalid koreader input")
View Source
var ErrLastAdmin = errors.New("cannot remove or demote the last admin")

ErrLastAdmin is returned when an access change or deletion would leave the library without an administrator.

View Source
var ErrReadOnly = errors.New("library database is read-only")
View Source
var ErrReadingTimeZoneRequired = errors.New("set your time zone before recording reading activity")
View Source
var ErrScopeShelfNotEligible = errors.New("scope shelf query cannot be used for access")

ErrScopeShelfNotEligible classifies a smart shelf whose complete query cannot safely be represented as a reader's access boundary.

View Source
var ErrScopeShelfNotVisible = errors.New("scope shelf is not visible")

ErrScopeShelfNotVisible is returned when an access scope tries to use a shelf that is not visible to the curator changing the account. Scope shelves follow the same shelf visibility rule as the UI: shared shelves plus the curator's own personal shelves. A scoped user's own personal shelves are never accepted as access policy.

View Source
var ErrSetupComplete = errors.New("initial account already exists")

ErrSetupComplete prevents unauthenticated setup from creating another admin.

View Source
var ErrTagCycle = errors.New("a branch cannot be moved inside itself")
View Source
var ErrTagNotFound = errors.New("tag not found")
View Source
var ErrTagPath = fmt.Errorf("use a path with non-empty parts and at most %d levels", bookmeta.MaxTagDepth)
View Source
var ErrTokenNameExists = errors.New("token name already in use")

ErrTokenNameExists is returned when a user already has a token with the given name (names are unique per user so they can be revoked by name).

View Source
var ErrUserExists = errors.New("username already taken")

ErrUserExists is returned when creating a user whose username is already taken (usernames are compared case-insensitively).

View Source
var ErrUserIDRequired = errors.New("user id required")

ErrUserIDRequired reports a missing user identity at the DB API boundary.

View Source
var ErrWriterLeaseHeld = errors.New("writer lease held by another process")
View Source
var ErrWriterTimeout = errors.New("timed out waiting for library writer")

ErrWriterTimeout means the writer was not acquired; no SQL was executed. It is distinct from a deadline or cancellation of the caller's context.

Functions

func AnnotationURI

func AnnotationURI(libraryID string, annotationID int64) string

func AssetContentSizes

func AssetContentSizes(q Queryer) (map[int64]struct{}, error)

AssetContentSizes returns recorded original and current sizes, including assets of trashed books and omitting NULL sizes. Import batches use this set only as a prefilter; content hashes determine duplicates.

func AuthorsByBookIDs

func AuthorsByBookIDs(queryer Queryer, bookIDs []int64) (map[int64][]AuthorRow, error)

AuthorsByBookIDs returns each book's authors in display order, keyed by book ID.

func BookListDependencies

func BookListDependencies(scope VisibilityScope, query string, sort BookSort, manualShelf bool) []string

BookListDependencies describes edits that may change a list's membership or order. Clients can patch other edits in place without interpreting queries. These are metadata field names, with separate cover, assets, author_sort, reading_status, added_at, and shelves changes. Nil means refresh on any edit. The wire names are shared with CatalogField in frontend/src/catalog-events.ts.

func BookURI

func BookURI(libraryID string, bookID int64) string

func BumpMetadataRev

func BumpMetadataRev(tx *Tx, bookIDs []int64) error

BumpMetadataRev marks books' writable assets as needing metadata write-back and touches updated_at. Text metadata and cover changes share this revision.

func CanAccessAsset

func CanAccessAsset(queryer Queryer, scope VisibilityScope, assetID int64) (bool, error)

func CanAccessBook

func CanAccessBook(queryer Queryer, scope VisibilityScope, bookID int64) (bool, error)

func CanAccessTrashedBook

func CanAccessTrashedBook(queryer Queryer, scope VisibilityScope, bookID int64) (bool, error)

func ClearMetadataWritebackAttempt

func ClearMetadataWritebackAttempt(execer Execer, assetID int64) error

func CountManualShelfOPDSPublications

func CountManualShelfOPDSPublications(queryer Queryer, scope VisibilityScope, shelfID int64) (int, error)

func CountOPDSPublications

func CountOPDSPublications(queryer Queryer, scope VisibilityScope) (int, error)

func CountSearchOPDSPublications

func CountSearchOPDSPublications(queryer Queryer, scope VisibilityScope, userID int64, q string) (int, error)

func CountTagOPDSPublications

func CountTagOPDSPublications(queryer Queryer, scope VisibilityScope, name string) (int, error)

func CountUsers

func CountUsers(queryer Queryer) (int, error)

CountUsers reports how many accounts exist. Zero means the server has not been bootstrapped yet (the first-run setup path applies).

func DSN

func DSN(path string) string

DSN builds a SQLite `file:` URI from a filesystem path, percent-encoding characters that are significant in a URI (notably `?`, `#` and spaces) so a path containing them opens the intended file instead of being parsed as query parameters / fragment. Path separators are preserved; relative paths stay relative (no `//` authority is introduced).

func DedupBookIDs

func DedupBookIDs(in []int64) []int64

DedupBookIDs returns positive IDs in their original order, without duplicates.

func DeleteOrphanAuthors

func DeleteOrphanAuthors(execer Execer) (int64, error)

DeleteOrphanAuthors removes authors rows no longer referenced by any book_authors (e.g. left behind when a book is re-linked to a different author spelling). Returns the number deleted; safe to run repeatedly.

func DeleteOrphanTags

func DeleteOrphanTags(execer Execer) error

func DeleteTag

func DeleteTag(tx *Tx, tagID int64) ([]int64, error)

func DeliveryBookForPlan

func DeliveryBookForPlan(queryer Queryer, scope VisibilityScope, bookID int64) (DeliveryBookRow, []DeliveryAssetRow, error)

func DismissDuplicateGroup

func DismissDuplicateGroup(tx *Tx, scope VisibilityScope, bookIDs []int64, userID int64) error

DismissDuplicateGroup records the exact live group the user dismissed. A later metadata edit or import changes the key/member set and should surface a fresh cleanup item; dismissals are not broad "never show this title again" suppressions.

func DuplicateMergeCoverSource

func DuplicateMergeCoverSource(queryer Queryer, scope VisibilityScope, survivorID int64, bookIDs []int64) (int64, error)

func EnsurePreferredPrimaryAsset

func EnsurePreferredPrimaryAsset(tx *Tx, bookID int64) error

EnsurePreferredPrimaryAsset chooses the preferred browser-reading format. Equal priorities keep the current primary, then prefer the oldest asset. A catalog default never changes per-user positions or annotations.

func HasAnyAsset

func HasAnyAsset(q Queryer) (bool, error)

func LibraryIdentity

func LibraryIdentity(queryer Queryer) (string, error)

LibraryIdentity is the stable namespace shared by catalog and export IDs.

func LibraryStorageStats

func LibraryStorageStats(q Queryer) (books int, sizeBytes int64, err error)

LibraryStorageStats reports the number of live books and the total on-disk size of their asset files, for the Storage settings health line. Size uses the current bytes, falling back to the imported size for assets never rewritten; trashed books are excluded because their files are pending purge.

func ListTags

func ListTags(queryer Queryer, scope VisibilityScope, kind TagKind, q string, limit int) ([]string, error)

ListTags returns names used by visible live books for suggestions and OPDS. It needs only tag identity, so neither counts nor book/ancestor pairs are built.

func ListTrashedBookIDs

func ListTrashedBookIDs(queryer Queryer, bookIDs ...int64) ([]int64, error)

ListTrashedBookIDs returns just the ids of trashed books. With no bookIDs it selects the whole trash; with ids it filters to the trashed subset of that explicit selection. Purge uses this inside its deletion transaction so a concurrent restore cannot change the selected set between inspection and commit.

func MarkMetadataWritebackError

func MarkMetadataWritebackError(execer Execer, assetID int64, writeErr error) error

func MarkMetadataWritebackSuccess

func MarkMetadataWritebackSuccess(tx *Tx, assetID int64, storagePath string, hash []byte, size int64, metadataRev int64) error

func MetadataWritebackFormatSQL

func MetadataWritebackFormatSQL(column string) string

MetadataWritebackFormatSQL returns a SQL predicate for asset format columns that can carry embedded metadata write-back. It is derived from format.SupportsMetadataWriteback so DB queries and diagnostics cannot drift from the renderer dispatch; the writeback partial index in migration 0001 mirrors the same key set.

func NewWriterLeaseOwner

func NewWriterLeaseOwner(label string) string

func ParseQuery

func ParseQuery(q string) string

ParseQuery converts a user query into the FTS5 MATCH expression. Relational filters such as no:cover and status:reading do not appear in the result.

func PlaceholderCoverText

func PlaceholderCoverText(queryer Queryer, bookID int64) (title, author string, found bool, err error)

PlaceholderCoverText returns the title and primary-author name for a book, the inputs for a generated fallback cover. found is false when the book does not exist (so the cover handler can keep returning 404 for unknown IDs).

func PrimaryAuthor

func PrimaryAuthor(queryer Queryer, bookID int64) (string, string, error)

PrimaryAuthor returns empty names when a book has no authors.

func PublicationURI

func PublicationURI(libraryID string, assetID int64) string

func PurgeAllTrashedBooks

func PurgeAllTrashedBooks(tx *Tx) (int, error)

PurgeAllTrashedBooks permanently deletes every trashed book without expanding their ids into SQL host parameters. Search is deleted first because its FTS5 rows are not covered by foreign-key cascades and the book subquery is no longer available after the authoritative rows are removed.

func PurgeBooks

func PurgeBooks(tx *Tx, bookIDs []int64) (int, error)

PurgeBooks permanently deletes the trashed subset of bookIDs in one batch. Search rows are explicit because FTS is not covered by foreign-key cascades; orphan authors are swept once after the whole set, not once per book. The caller captures file paths before this call and unlinks only after commit.

func QueryTerm

func QueryTerm(field, value string) string

QueryTerm builds a qualified search term (for example series:"Name"), doubling embedded quotes so parseSearchQuery reconstructs the literal value.

func RecordAssetRestore

func RecordAssetRestore(database Execer, assetID int64, hash []byte, size int64) error

RecordAssetRestore keeps write-back acknowledgement only when restoring the exact bytes it described. Original import identity is never changed.

func RenameOrMergeAuthor

func RenameOrMergeAuthor(tx *Tx, oldName, newName, newSortName string) ([]int64, error)

RenameOrMergeAuthor renames an author or merges its links into an existing author with the exact newName, preserving the target's sort_name and avoiding duplicate book links. It returns the affected book IDs; the caller handles metadata revisions, search indexing, and relayout.

func ResourceURI

func ResourceURI(publicationURI, href string) string

func RestoreBook

func RestoreBook(execer Execer, bookID int64) error

RestoreBook clears the trash flags, returning the book to the live catalog. Returns sql.ErrNoRows when no *trashed* book has this id.

func RoleAtLeast

func RoleAtLeast(role, minRole string) bool

func RoleRank

func RoleRank(role string) int

func SetAuthorSortName

func SetAuthorSortName(tx *Tx, name, sortName string) ([]int64, error)

SetAuthorSortName overrides an author's sort_name (the canonical-path sort key) without touching the display name. Returns the book IDs the author is linked to; the caller owns metadata_rev/search/relayout bookkeeping. sort_name selects both the bucket and the author folder, so a change moves files for books where the author is primary.

func SetBookTags

func SetBookTags(tx *Tx, bookID int64, kind TagKind, names []string) error

SetBookTags replaces memberships of one kind, retaining the other kind and existing dictionary spelling. Names must be trimmed, non-empty, comma-free, and unique by bookmeta.TagKey. Callers replacing existing links clean up orphans once per operation or batch.

func SharedShelfNamesOwnedBy

func SharedShelfNamesOwnedBy(queryer Queryer, ownerID int64) ([]string, error)

SharedShelfNamesOwnedBy returns the names of shared shelves owned by a user, ordered by name. Deleting the user cascades these away for the whole household (shelves.owner_id ON DELETE CASCADE), so the user-delete UI warns with this list before confirming.

func SoftDeleteBook

func SoftDeleteBook(execer Execer, bookID int64, deletedBy int64) error

SoftDeleteBook marks a live book as trashed: it drops out of every normal projection (browse / search / cleanup / shelves — all filter deleted_at IS NULL) while its row and files stay on disk until an admin purge. deletedBy records who trashed it, for a legible "Deleted by X — Restore?" trash view. Returns sql.ErrNoRows when no *live* book has this id (unknown id or already trashed), so the handler can answer 404 / no-op uniformly.

func StorePageCount

func StorePageCount(execer Execer, assetID int64, hash []byte, pages int) (bool, error)

StorePageCount fills a missing count only for the bytes that were measured. The next metadata writeback includes it; counting alone does not advance the book's revision or schedule a file update.

func TagSearchKeys

func TagSearchKeys(kind TagKind, tags []string) string

TagSearchKeys indexes canonical, unique direct memberships from the catalog and their proper ancestors. Flat tags need only one token. Branch search and shelf access match either the direct token or the ancestor token.

func TagsByBookIDs

func TagsByBookIDs(queryer Queryer, bookIDs []int64) (map[int64]BookTags, error)

TagsByBookIDs loads ordered, canonical names in bounded batches, including Trash.

func UpdateSearchIndex

func UpdateSearchIndex(tx *Tx, bookID int64) error

UpdateSearchIndex rebuilds the search table row for a book from the relational catalog.

func UpsertBookAuthors

func UpsertBookAuthors(tx *Tx, bookID int64, authors []bookmeta.AuthorMeta) (primaryName, primarySortName string, err error)

UpsertBookAuthors replaces a book's ordered author links, keeping the first occurrence of each exact name. It returns the primary author's name and sort name, or empty strings when the list is empty.

Input authors must have SortName filled. Existing authors retain their stored sort_name so import and edit honor the same storage path overrides. Callers replacing existing links should follow with DeleteOrphanAuthors.

func UpsertMetadataWritebackAttempt

func UpsertMetadataWritebackAttempt(execer Execer, attempt MetadataWritebackAttempt) error

func UserScopeShelfIDs

func UserScopeShelfIDs(queryer Queryer, userID int64) ([]int64, error)

func ValidDeliveryPreset

func ValidDeliveryPreset(preset string) bool

func ValidReadingStatus

func ValidReadingStatus(status string) bool

func ValidRole

func ValidRole(role string) bool

Types

type Annotation

type Annotation struct {
	ID            int64
	UserID        int64
	AssetID       int64
	Locator       Locator
	Quote         string
	ContextBefore string
	ContextAfter  string
	Note          string
	Color         string
	Revision      int64
	Deleted       bool
	CreatedAt     int64
	UpdatedAt     int64
}

func ListAnnotations

func ListAnnotations(queryer Queryer, userID, assetID int64) ([]Annotation, error)

func ListBookAnnotations

func ListBookAnnotations(queryer Queryer, userID, bookID int64) ([]Annotation, error)

type AnnotationCreate

type AnnotationCreate struct {
	Locator       Locator
	Quote         string
	ContextBefore string
	ContextAfter  string
	Note          string
	Color         string
}

type AnnotationUpdate

type AnnotationUpdate struct {
	Revision int64
	Note     *string
	Color    *string
}

type AppToken

type AppToken struct {
	ID         int64
	Name       string
	Token      string
	CreatedAt  int64
	LastUsedAt sql.NullInt64
}

AppToken is a long-lived per-device credential ("app password"). Its secret remains available to its owner so device setup can be resumed at any time.

func ListAppTokens

func ListAppTokens(queryer Queryer, userID int64) ([]AppToken, error)

ListAppTokens returns a user's tokens, including their secrets, newest first.

type AssetRow

type AssetRow struct {
	ID               int64
	Extension        string
	Format           format.Format
	StoragePath      string
	OriginalFilename string
	BookID           int64
	IsPrimary        bool
	PageCount        int
	// Size is COALESCE(current_size, original_size, 0) from the row, so UI/list
	// paths report byte sizes without a per-asset os.Stat (matters on a NAS root).
	Size int64
}

func AssetsByBookIDs

func AssetsByBookIDs(queryer Queryer, bookIDs []int64) ([]AssetRow, error)

func AssetsForTrashedBooks

func AssetsForTrashedBooks(queryer Queryer) ([]AssetRow, error)

AssetsForTrashedBooks returns every asset whose book is currently in Trash. Empty-trash uses this dedicated projection so its SQL shape stays constant at large-library scale instead of expanding one host parameter per book.

type AssetWithAuthorRow

type AssetWithAuthorRow struct {
	ID               int64
	BookID           int64
	StoragePath      string
	OriginalFilename string
	Extension        string
	Format           format.Format
	OriginalHash     []byte
	CurrentHash      []byte
	OriginalSize     sql.NullInt64
	CurrentSize      sql.NullInt64
	Title            string
	SortTitle        string
	Series           string
	SeriesIndex      string
	AuthorName       string
	AuthorSortName   string
}

func AllAssetsWithPrimaryAuthor

func AllAssetsWithPrimaryAuthor(queryer Queryer) ([]AssetWithAuthorRow, error)

type AuthorCount

type AuthorCount struct {
	Name      string
	SortName  string
	BookCount int
}

AuthorCount is an author plus how many books reference it. Used by the manage-authors screen.

func GetAuthorInfo

func GetAuthorInfo(queryer Queryer, scope VisibilityScope, name string) (AuthorCount, bool, error)

GetAuthorInfo returns one author's sort_name and the number of books crediting it, looked up by exact name, plus whether such an author exists. Author identity is the exact name string (matching the import/edit reuse-by-name rule), so the lookup is exact-match, not fuzzy. Powers the book-edit convergence prompt, which asks how many *other* books still credit a just-renamed author.

func ListAuthorCountsPage

func ListAuthorCountsPage(queryer Queryer, scope VisibilityScope, afterSortName, afterName string, limit int) ([]AuthorCount, error)

ListAuthorCountsPage returns a keyset page ordered by sort_name and exact name.

type AuthorNameRow

type AuthorNameRow struct {
	Name     string
	SortName string
}

func ListAuthorNames

func ListAuthorNames(queryer Queryer, scope VisibilityScope, q string, limit int) ([]AuthorNameRow, error)

ListAuthorNames returns distinct authors that are referenced by at least one book (i.e. not orphans), optionally filtered by a case-insensitive substring, ordered by sort_name. Used for edit autocomplete so a re-spelling can reuse an existing author instead of spawning a duplicate.

type AuthorRow

type AuthorRow struct {
	BookID   int64
	Name     string
	SortName string
	Role     string
	Order    int
}

type BookCoverRow

type BookCoverRow struct {
	ID              int64
	CoverVersion    int
	ManualOverrides string
}

func AllBookCovers

func AllBookCovers(queryer Queryer) ([]BookCoverRow, error)

AllBookCovers returns the persisted cover state used by library check and repair to validate or rebuild the derived cover files.

type BookDetailRow

type BookDetailRow struct {
	BookSummaryRow
	SortTitle   string
	Description sql.NullString
	Language    sql.NullString
	Publisher   sql.NullString
	Identifiers sql.NullString
	AddedAt     int64
	UpdatedAt   int64
}

func GetBook

func GetBook(queryer Queryer, scope VisibilityScope, bookID int64) (BookDetailRow, error)

type BookJump

type BookJump struct {
	Label  string
	Offset int
}

func ListBookJumps

func ListBookJumps(queryer Queryer, scope VisibilityScope, sort BookSort) ([]BookJump, int, error)

ListBookJumps streams the indexed sort key so each offset exactly matches the list order without retaining the catalog in memory. An adversarial catalog with too many distinct Unicode labels hides the affordance instead of producing an unbounded response.

type BookSequenceItem

type BookSequenceItem struct {
	ID    int64
	Title string
}

type BookSequenceWindow

type BookSequenceWindow struct {
	Items        []BookSequenceItem
	CurrentIndex int
	Total        int
}

func BookSequenceInList

func BookSequenceInList(queryer Queryer, scope VisibilityScope, userID int64, bookID int64, q string, sort BookSort, before, after int) (BookSequenceWindow, error)

func BookSequenceInManualShelf

func BookSequenceInManualShelf(queryer Queryer, scope VisibilityScope, bookID int64, shelfID int64, sort BookSort, before, after int) (BookSequenceWindow, error)

type BookSort

type BookSort string
const (
	SortAdded     BookSort = "added"
	SortTitle     BookSort = "title"
	SortAuthor    BookSort = "author"
	SortYear      BookSort = "year"
	SortSeries    BookSort = "series"
	SortRelevance BookSort = "relevance"
)

type BookSummaryRow

type BookSummaryRow struct {
	ID           int64
	Title        string
	Series       sql.NullString
	SeriesIndex  sql.NullFloat64
	CoverVersion int
	Date         sql.NullString
}

BookSummaryRow is the list/cleanup projection — the columns every books listing needs (scanBookSummary reads exactly these). BookDetailRow extends it with the detail-only fields the single-book view loads, so a list query can't hand back fields it never selected.

func BookSummaryRowsByIDs

func BookSummaryRowsByIDs(queryer Queryer, scope VisibilityScope, ids []int64) ([]BookSummaryRow, error)

BookSummaryRowsByIDs returns list-projection rows for the given books visible in scope, so a mutation handler can hand updated summaries back to the client.

func ListBooks

func ListBooks(queryer Queryer, scope VisibilityScope, userID int64, q string, sort BookSort, limit, offset int) ([]BookSummaryRow, error)

func ListBooksInManualShelf

func ListBooksInManualShelf(queryer Queryer, scope VisibilityScope, shelfID int64, sort BookSort, limit, offset int) ([]BookSummaryRow, error)

type BookTags

type BookTags struct {
	Genres []string
	Tags   []string
}

BookTags holds the two independently ordered parts of the shared dictionary.

type BookWritebackState

type BookWritebackState struct {
	Writable int
	Dirty    int
}

BookWritebackState summarizes one book's writable assets for the book-page action: how many assets can carry embedded metadata, and how many of those are behind the current book metadata (the enabled/"up to date" signal).

func GetBookWritebackState

func GetBookWritebackState(queryer Queryer, bookID int64) (BookWritebackState, error)

GetBookWritebackState reports the writable/dirty asset counts for one live book. A trashed book reports zero (its detail page 404s anyway).

type BulkEditRow

type BulkEditRow struct {
	ID          int64
	Genres      []string
	Tags        []string
	Series      sql.NullString
	SeriesIndex sql.NullFloat64
	Overrides   sql.NullString
}

BulkEditRow carries the mutable metadata a bulk operation reads before computing its transform: the current tags/series values and the manual-override set to merge into.

func BooksForBulkEdit

func BooksForBulkEdit(queryer Queryer, scope VisibilityScope, ids []int64) ([]BulkEditRow, error)

BooksForBulkEdit loads the current bulk-editable state for the given live books that are visible in scope. Books that are missing, trashed, or out of scope are simply omitted, so the caller can treat the returned set as the authoritative list of books it may mutate.

type CleanupCounts

type CleanupCounts struct {
	MissingCover   int
	MissingAuthor  int
	NoGenresOrTags int
	NoDescription  int
}

func GetCleanupCounts

func GetCleanupCounts(queryer Queryer, scope VisibilityScope) (CleanupCounts, error)

type ContinueReadingRow

type ContinueReadingRow struct {
	BookSummaryRow
	AssetID   int64
	Progress  float64
	UpdatedAt int64
}

func ListContinueReading

func ListContinueReading(queryer Queryer, scope VisibilityScope, userID int64, limit int) ([]ContinueReadingRow, error)

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB owns independent read and write pools for one library. Readers cannot write; the writer has one connection, so concurrent writes wait in Go rather than competing for SQLite's write lock. All SQL inside a write transaction, including reads, must use its Tx.

func InitPath

func InitPath(path string) (*DB, error)

InitPath opens a SQLite DB at path using filesystem-aware pragmas.

func InitPathReadOnly

func InitPathReadOnly(path string) (*DB, error)

InitPathReadOnly opens a SQLite DB at path in read-only mode using filesystem-aware pragmas. It neither runs migrations nor changes journal mode.

func (*DB) AddBookToShelf

func (db *DB) AddBookToShelf(ctx context.Context, shelfID int64, viewerID int64, bookID int64) error

func (*DB) AddBooksToShelf

func (db *DB) AddBooksToShelf(ctx context.Context, shelfID int64, viewerID int64, bookIDs []int64) (int, error)

AddBooksToShelf adds every bookID to the manual shelf in one transaction, skipping any already present, and returns how many rows were newly inserted. Each insert recomputes the next position, so the selection is appended in the given order after whatever the shelf already held.

func (*DB) AppTokenUserID

func (db *DB) AppTokenUserID(ctx context.Context, token string) (int64, bool, error)

AppTokenUserID resolves a raw token to its owning user id, reporting whether a live token matched. It opportunistically records last_used_at (throttled to at most once per hour, like session bumps) so ordinary OPDS browsing does not turn every request into a write.

func (*DB) BeginWrite

func (db *DB) BeginWrite(ctx context.Context) (*Tx, error)

BeginWrite waits for the writer and begins an immediate SQLite transaction. Queueing has a finite deadline; the transaction keeps the caller's context. Reserve Conn separately: sql.DB.BeginTx uses one context for both waiting and the transaction, so a writer-wait deadline would also abort the transaction. Use tx for every operation until commit or rollback: acquiring the writer again from inside the transaction would wait on itself.

func (*DB) CacheAssetKOReaderHash

func (db *DB) CacheAssetKOReaderHash(ctx context.Context, assetID int64, currentHash []byte, hash string) error

CacheAssetKOReaderHash records an original download with a short writer deadline. The downloaded hash is kept even after a concurrent replacement; the current-file cache is updated only while the expected content hash matches.

func (*DB) CachePositionConversion

func (db *DB) CachePositionConversion(ctx context.Context, state *ReaderState) (bool, error)

CachePositionConversion fills coordinates only while the reading revision remains current, without changing the observation's source or timestamp.

func (*DB) CheckpointWebReadingSession

func (db *DB) CheckpointWebReadingSession(ctx context.Context, userID, assetID int64, sourceID string, checkpoint ReadingActivityCheckpoint, now time.Time) (ReadingActivityResult, error)

CheckpointWebReadingSession records cumulative time within a visible segment. Retries and reordered checkpoints cannot count time twice. Old segments are ignored; if their final report was lost, unreported time remains uncounted.

func (*DB) Close

func (db *DB) Close() error

func (*DB) CreateAnnotation

func (db *DB) CreateAnnotation(ctx context.Context, userID, assetID int64, input AnnotationCreate) (Annotation, error)

func (*DB) CreateAppToken

func (db *DB) CreateAppToken(ctx context.Context, userID int64, name string) (*AppToken, error)

CreateAppToken issues and stores a random token for a user. name must be non-empty and unique for that user.

func (*DB) CreateDeliveryDevice

func (db *DB) CreateDeliveryDevice(ctx context.Context, userID int64, name, email, preset string, isDefault bool) (*DeliveryDevice, error)

func (*DB) CreateDeliveryJob

func (db *DB) CreateDeliveryJob(ctx context.Context, job DeliveryJob) (*DeliveryJob, error)

func (*DB) CreateInitialAdmin

func (db *DB) CreateInitialAdmin(ctx context.Context, username, password string) (*User, error)

CreateInitialAdmin creates an administrator only while the library has no accounts. The check and insertion share the same write transaction.

func (*DB) CreateKoboConnection

func (db *DB) CreateKoboConnection(ctx context.Context, userID, shelfID int64) (*KoboConnection, error)

CreateKoboConnection creates a retrievable URL credential for a selected shelf.

func (*DB) CreateShelf

func (db *DB) CreateShelf(ctx context.Context, ownerID int64, visibility ShelfVisibility, name string, kind ShelfKind, query string) (*Shelf, error)

CreateShelf inserts either a manual shelf or a query-backed shelf. ownerID is always the shelf owner; visibility controls whether other users can see it.

func (*DB) CreateUser

func (db *DB) CreateUser(ctx context.Context, username, password, role string) (*User, error)

CreateUser inserts a new account with the given clear-text password (hashed here). The username is normalized; a collision returns ErrUserExists.

func (*DB) CreateUserWithAccess

func (db *DB) CreateUserWithAccess(ctx context.Context, username, password string, access UserAccess) (*User, error)

CreateUserWithAccess inserts an account, its default personal shelf, and its final shelf scope in one transaction.

func (*DB) DeleteAnnotation

func (db *DB) DeleteAnnotation(ctx context.Context, userID, assetID, annotationID, revision int64) error

func (*DB) DeleteDeliveryDevice

func (db *DB) DeleteDeliveryDevice(ctx context.Context, userID, deviceID int64) error

func (*DB) DeleteKoboConnection

func (db *DB) DeleteKoboConnection(ctx context.Context, userID int64) error

func (*DB) DeleteShelf

func (db *DB) DeleteShelf(ctx context.Context, shelfID int64, viewerID int64) error

func (*DB) DeleteUser

func (db *DB) DeleteUser(ctx context.Context, userID int64) error

DeleteUser removes an account by id.

func (*DB) ExecBestEffort

func (db *DB) ExecBestEffort(ctx context.Context, query string, args ...any) (bool, error)

ExecBestEffort bounds optional bookkeeping, such as credential timestamps, to a short deadline. It returns false without an error if the write times out; caller cancellation and other database errors still propagate. Do not use it for required mutations, including credential creation or revocation.

func (*DB) KOReaderUserID

func (db *DB) KOReaderUserID(ctx context.Context, key string) (int64, bool, error)

KOReaderUserID resolves KOSync's MD5(password) through its stored lookup key. App passwords identify their owner without the client's username.

func (*DB) KoboConnectionByToken

func (db *DB) KoboConnectionByToken(ctx context.Context, token string) (*KoboConnection, bool, error)

KoboConnectionByToken authenticates a Kobo URL using its device credential. The last-used timestamp is throttled so cover and download traffic does not turn every request into a database write.

func (*DB) Read

func (db *DB) Read(ctx context.Context) Queryer

Read binds query helpers to the caller's context without reserving a connection. Inside a transaction, pass Tx instead; it already owns the caller's context.

func (*DB) RecoverDeliveryJobs

func (db *DB) RecoverDeliveryJobs(ctx context.Context) error

RecoverDeliveryJobs preserves work which is safe to repeat while refusing to automatically duplicate a possibly completed SMTP send.

func (*DB) RememberKOReaderHash

func (db *DB) RememberKOReaderHash(ctx context.Context, assetID int64, hash, conversion string) error

RememberKOReaderHash records a converted download's hash and format with a short writer deadline, leaving the original file's cache unchanged.

func (*DB) RemoveBookFromShelf

func (db *DB) RemoveBookFromShelf(ctx context.Context, shelfID int64, viewerID int64, bookID int64) error

func (*DB) RemoveBooksFromShelf

func (db *DB) RemoveBooksFromShelf(ctx context.Context, shelfID int64, viewerID int64, bookIDs []int64) (int, error)

RemoveBooksFromShelf drops every bookID from the manual shelf in one statement and returns how many rows were actually removed.

func (*DB) ResetReaderState

func (db *DB) ResetReaderState(ctx context.Context, userID, assetID int64) error

ResetReaderState clears the position and advances its revision. Repeating a reset of an already cleared position is a no-op.

func (*DB) RevokeAppToken

func (db *DB) RevokeAppToken(ctx context.Context, userID int64, name string) error

RevokeAppToken deletes a user's token by name. Returns sql.ErrNoRows if no such token exists for that user.

func (*DB) RevokeAppTokenByID

func (db *DB) RevokeAppTokenByID(ctx context.Context, userID int64, tokenID int64) error

RevokeAppTokenByID deletes a user's token by id. It is used by the web UI so token names never have to become URL path components.

func (*DB) SaveKOReaderProgress

func (db *DB) SaveKOReaderProgress(ctx context.Context, userID int64, input KOReaderProgress) (*KOReaderState, error)

SaveKOReaderProgress saves a position and advances a matched book's reading status. Unchanged uploads and echoes preserve the saved observation.

func (*DB) SaveKoboReading

func (db *DB) SaveKoboReading(ctx context.Context, userID, assetID int64, input KoboReadingUpdate) (KoboReadingResult, error)

SaveKoboReading accepts independently dated bookmark and status updates. Without an explicit status, a changed bookmark can advance reading status. Older uploads cannot replace a newer position, including a deliberate rewind or reset. Device clocks are expected to agree with the server clock.

func (*DB) SaveOPDSProgression

func (db *DB) SaveOPDSProgression(ctx context.Context, userID, assetID int64, input ReaderPositionWrite, modified time.Time, expected *int64) (*ReaderState, error)

SaveOPDSProgression checks an optional ETag under the writer transaction. Without one, client time is only a hint for rejecting stale backward moves. The transport parses modified; it is never persisted or returned as server time.

func (*DB) SaveReaderState

func (db *DB) SaveReaderState(ctx context.Context, userID, assetID int64, input ReaderPositionWrite, source ReadingStatusSource) (*ReaderState, ReadingStatusChange, error)

SaveReaderState saves a position and advances its book's reading status atomically.

func (*DB) SaveUserSettings

func (db *DB) SaveUserSettings(ctx context.Context, userID int64, patch UserSettingsPatch) (*UserSettings, error)

func (*DB) SetDeliveryJobSize

func (db *DB) SetDeliveryJobSize(ctx context.Context, jobID, size int64) error

func (*DB) SetDeliveryJobStatus

func (db *DB) SetDeliveryJobStatus(ctx context.Context, jobID int64, status, errorMessage string) error

func (*DB) SetKoboConnectionShelf

func (db *DB) SetKoboConnectionShelf(ctx context.Context, userID, shelfID int64) (*KoboConnection, error)

SetKoboConnectionShelf preserves the credential and revision history. The next sync reconciles the new shelf against the previous one, including removals.

func (*DB) SetReadingStatus

func (db *DB) SetReadingStatus(ctx context.Context, userID int64, bookID int64, status string, source ReadingStatusSource) (ReadingStatusChange, error)

func (*DB) SetUserPassword

func (db *DB) SetUserPassword(ctx context.Context, userID int64, password string, keepSessionHash []byte) error

SetUserPassword replaces the password and revokes browser sessions atomically. keepSessionHash preserves the session initiating a self-change; nil revokes every session. Device credentials are unaffected.

func (*DB) StartWebReadingSession

func (db *DB) StartWebReadingSession(ctx context.Context, userID, assetID int64, sourceID string, segment int64, now time.Time) (ReadingActivityResult, error)

StartWebReadingSession starts or resumes the user's sole active web session. Repeating a segment's start is idempotent, including after closure or takeover.

func (*DB) SyncKoboConnection

func (db *DB) SyncKoboConnection(ctx context.Context, connectionID, after int64, limit int) ([]KoboChange, int64, bool, error)

SyncKoboConnection reconciles the selected shelf and reads one stable revision page in the same transaction. A retry with the same cursor therefore returns the same logical page unless real source data changed in between.

func (*DB) TouchReader

func (db *DB) TouchReader(ctx context.Context, userID, assetID int64, source ReadingStatusSource) error

TouchReader records opening a book and advances unread books to reading.

func (*DB) Transact

func (db *DB) Transact(ctx context.Context, fn func(tx *Tx) error) error

Transact runs fn in a transaction using the caller's context. It rolls back if fn returns an error and commits after fn succeeds.

func (*DB) UndoAutomaticReadingStatus

func (db *DB) UndoAutomaticReadingStatus(ctx context.Context, userID int64, bookID int64, eventID int64) (ReadingStatusChange, error)

func (*DB) UpdateAnnotation

func (db *DB) UpdateAnnotation(ctx context.Context, userID, assetID, annotationID int64, input AnnotationUpdate) (Annotation, error)

func (*DB) UpdateDeliveryDevice

func (db *DB) UpdateDeliveryDevice(ctx context.Context, userID int64, device DeliveryDevice) (*DeliveryDevice, error)

func (*DB) UpdateShelf

func (db *DB) UpdateShelf(ctx context.Context, shelfID int64, viewerID int64, name, query string, visibility ShelfVisibility) (*Shelf, error)

UpdateShelf edits a shelf without changing its type. Query shelves receive a new search string; manual shelves ignore query and keep explicit membership. visibility changes whether the shelf is personal or shared without changing ownership.

func (*DB) UpdateUserAccess

func (db *DB) UpdateUserAccess(ctx context.Context, userID int64, access UserAccess) (*User, error)

func (*DB) Write

func (db *DB) Write(ctx context.Context) Execer

Write binds SQL helpers to the caller's context. Each Exec acquires and releases the writer independently; use Transact when statements must be atomic.

type DeliveryAssetRow

type DeliveryAssetRow struct {
	ID        int64
	Filename  string
	Extension string
	Format    format.Format
	Size      int64
	IsPrimary bool
}

type DeliveryBookRow

type DeliveryBookRow struct {
	ID      int64
	Title   string
	Authors string
}

type DeliveryDevice

type DeliveryDevice struct {
	ID        int64
	UserID    int64
	Name      string
	Email     string
	Preset    string
	IsDefault bool
	CreatedAt int64
	UpdatedAt int64
}

func DefaultDeliveryDevice

func DefaultDeliveryDevice(queryer Queryer, userID int64) (*DeliveryDevice, error)

func GetDeliveryDevice

func GetDeliveryDevice(queryer Queryer, userID, deviceID int64) (*DeliveryDevice, error)

func ListDeliveryDevices

func ListDeliveryDevices(queryer Queryer, userID int64) ([]DeliveryDevice, error)

type DeliveryJob

type DeliveryJob struct {
	ID          int64
	UserID      int64
	DeviceID    sql.NullInt64
	DeviceName  string
	DeviceEmail string
	Preset      string
	AssetID     sql.NullInt64
	Title       string
	Target      sql.NullString
	Filename    string
	SizeBytes   sql.NullInt64
	Status      string
	// Error is a user-facing problem message: an error for failed jobs,
	// or a conversion warning for sent jobs. Status alone drives the lifecycle.
	Error     string
	CreatedAt int64
	UpdatedAt int64
	SentAt    sql.NullInt64
}

func GetDeliveryJob

func GetDeliveryJob(queryer Queryer, userID, jobID int64) (*DeliveryJob, error)

func GetDeliveryJobByID

func GetDeliveryJobByID(queryer Queryer, jobID int64) (*DeliveryJob, error)

func ListDeliveryJobs

func ListDeliveryJobs(queryer Queryer, userID int64, limit int) ([]DeliveryJob, error)

func NextQueuedDeliveryJob

func NextQueuedDeliveryJob(queryer Queryer) (*DeliveryJob, error)

NextQueuedDeliveryJob returns the oldest durable delivery waiting for the single server worker. The writer lease guarantees there is only one worker process, so a separate claim/lock protocol would add no useful safety here.

type DuplicateGroup

type DuplicateGroup struct {
	Reason string
	Key    string
	Books  []BookSummaryRow
}

Duplicate detection is intentionally conservative: the current detector groups live books by normalized title + primary author only. GetPossibleDuplicates returns the total number of non-dismissed groups before maxGroups pagination, then materializes up to maxGroups of those groups for display.

func GetPossibleDuplicates

func GetPossibleDuplicates(queryer Queryer, scope VisibilityScope, maxGroups int) (int, []DuplicateGroup, error)

GetPossibleDuplicates scans live books and groups normalized keys in Go rather than in SQL — exact SQL grouping would need a denormalized Unicode-aware dedup key column. Deliberate; revisit only if duplicate suggestions prove hot on a large real library, not as a drive-by rewrite.

type DuplicateMergeRequest

type DuplicateMergeRequest struct {
	SurvivorID  int64
	BookIDs     []int64
	DeletedBy   int64
	CoverFromID int64
}

type DuplicateMergeResult

type DuplicateMergeResult struct {
	SurvivorID        int64
	TrashedIDs        []int64
	FilledDescription bool
	FilledCover       bool
}

func MergeDuplicateBooks

func MergeDuplicateBooks(tx *Tx, scope VisibilityScope, req DuplicateMergeRequest) (DuplicateMergeResult, error)

type Execer

type Execer interface {
	Exec(query string, args ...any) (sql.Result, error)
}

Execer writes through the library's single writer or an existing transaction.

type KOReaderHashTarget

type KOReaderHashTarget struct {
	AssetID int64
	BookID  int64
}

KOReaderHashTarget identifies a unique live asset and/or book for a document. Each ID is zero when unknown or ambiguous. Multiple assets of one book have a BookID but no AssetID.

func ResolveKOReaderHash

func ResolveKOReaderHash(queryer Queryer, documentHash string) (KOReaderHashTarget, error)

type KOReaderProgress

type KOReaderProgress struct {
	DocumentHash string
	Position     string
	Progress     float64
	DeviceID     string
	DeviceName   string
}

type KOReaderState

type KOReaderState struct {
	Position   string
	Progress   float64
	DeviceID   string
	DeviceName string
	UpdatedAt  int64
}

KOReaderState is the native KOSync response, whether the book is in the library or not.

func GetExternalKOReaderState

func GetExternalKOReaderState(queryer Queryer, userID int64, document string) (*KOReaderState, error)

GetExternalKOReaderState reads the native fallback without resolving a library asset.

type KoboAsset

type KoboAsset struct {
	AssetID int64
	BookID  int64
	Format  string
	AddedAt int64
}

func KoboAssetForConnection

func KoboAssetForConnection(queryer Queryer, scope VisibilityScope, connectionID, assetID int64) (*KoboAsset, error)

KoboAssetForConnection checks the last reconciled projection and current visibility. Shelf additions/removals enter the projection at library sync.

type KoboChange

type KoboChange struct {
	KoboPublication
	Revision      int64
	FirstRevision int64 // Start of the current appearance; re-adding a book starts a new one.
	Present       bool
	ChangedAt     int64
}

type KoboConnection

type KoboConnection struct {
	ID         int64
	UserID     int64
	ShelfID    sql.NullInt64
	ShelfName  string
	Token      string
	Revision   int64
	CreatedAt  int64
	UpdatedAt  int64
	LastUsedAt sql.NullInt64
}

func KoboConnectionForUser

func KoboConnectionForUser(queryer Queryer, userID int64) (*KoboConnection, error)

type KoboPosition

type KoboPosition struct {
	Source                 string   `json:"source,omitzero"`
	Type                   string   `json:"type,omitzero"`
	Fragment               string   `json:"fragment,omitzero"`
	ChapterProgressPercent *float64 `json:"chapter_progress_percent,omitzero"`
}

KoboPosition retains the device's location and its progress within the chapter. Unknown location types can still round-trip through native sync.

func (KoboPosition) Equal

func (p KoboPosition) Equal(other KoboPosition) bool

func (KoboPosition) IsZero

func (p KoboPosition) IsZero() bool

func (*KoboPosition) Scan

func (p *KoboPosition) Scan(value any) error

func (KoboPosition) Value

func (p KoboPosition) Value() (driver.Value, error)

type KoboPublication

type KoboPublication struct {
	KoboAsset
	Size          int64
	Title         string
	Description   string
	Publisher     string
	PublishedDate string
	Language      string
	Series        string
	SeriesIndex   sql.NullFloat64
	Authors       []string
	ModifiedAt    int64
	CoverVersion  int
}

KoboPublication is the metadata needed by the native Kobo adapter.

func KoboPublicationForAsset

func KoboPublicationForAsset(queryer Queryer, assetID int64) (*KoboPublication, error)

KoboPublicationForAsset loads metadata after the caller checks access.

type KoboReadingResult

type KoboReadingResult struct {
	PositionChanged bool
	StatusChanged   bool
}

type KoboReadingUpdate

type KoboReadingUpdate struct {
	Position          *KoboPosition
	Progress          *float64
	PositionUpdatedAt int64 // Unix seconds from CurrentBookmark.LastModified.
	Status            string
	StatusUpdatedAt   int64 // Unix seconds from StatusInfo.LastModified.
	DeviceID          string
	DeviceName        string
}

type Locator

type Locator struct {
	CFI      string `json:"cfi,omitzero"`
	Path     string `json:"path,omitzero"`
	Fragment string `json:"fragment,omitzero"` // URI fragment without #, retained for external readers.
	Page     int    `json:"page,omitzero"`     // One-based fixed-layout page number.
	Rects    []Rect `json:"rects,omitempty"`
}

Locator identifies a position or selection within one asset. Reading positions with an empty locator fall back to progress. PDF rectangles use unrotated page coordinates, independent of zoom.

func (Locator) Equal

func (locator Locator) Equal(other Locator) bool

func (Locator) IsZero

func (locator Locator) IsZero() bool

func (*Locator) Scan

func (locator *Locator) Scan(value any) error

SQL reads decode system-written values; validation belongs to writes.

func (Locator) Value

func (locator Locator) Value() (driver.Value, error)

type MetadataWritebackAssetRow

type MetadataWritebackAssetRow struct {
	AssetID      int64
	BookID       int64
	StoragePath  string
	Format       format.Format
	CurrentHash  []byte
	CurrentSize  sql.NullInt64
	MetadataRev  int64
	WritebackRev int64
	Error        string
}

MetadataWritebackAssetRow is one writable asset considered for embedded metadata write-back.

func GetMetadataWritebackAsset

func GetMetadataWritebackAsset(queryer Queryer, assetID int64) (MetadataWritebackAssetRow, error)

GetMetadataWritebackAsset loads the current writable write-back projection for one live asset. It is the freshness check before a physical write attempt.

func ListAllMetadataWritebackAssets

func ListAllMetadataWritebackAssets(queryer Queryer, scope VisibilityScope, limit int) ([]MetadataWritebackAssetRow, error)

ListAllMetadataWritebackAssets returns every live writable asset, including clean rows. It is for explicit maintenance runs such as --all.

func ListAutomaticMetadataWritebackAssets

func ListAutomaticMetadataWritebackAssets(queryer Queryer, scope VisibilityScope, failedBefore int64, limit int) ([]MetadataWritebackAssetRow, error)

ListAutomaticMetadataWritebackAssets returns a bounded automatic write-back batch. Failed assets are eligible when assets.updated_at <= failedBefore; dirty assets without a recorded failure are eligible immediately.

func ListDirtyMetadataWritebackAssets

func ListDirtyMetadataWritebackAssets(queryer Queryer, scope VisibilityScope, limit int) ([]MetadataWritebackAssetRow, error)

ListDirtyMetadataWritebackAssets returns writable live assets whose embedded metadata is behind the catalog revision.

func ListFailedMetadataWritebackAssets

func ListFailedMetadataWritebackAssets(queryer Queryer, scope VisibilityScope, limit int) ([]MetadataWritebackAssetRow, error)

ListFailedMetadataWritebackAssets returns dirty writable live assets whose last write-back attempt failed.

func ListMetadataWritebackAssetsByBookIDs

func ListMetadataWritebackAssetsByBookIDs(queryer Queryer, scope VisibilityScope, bookIDs []int64, limit int) ([]MetadataWritebackAssetRow, error)

ListMetadataWritebackAssetsByBookIDs returns writable live assets for the selected books, regardless of dirty state.

type MetadataWritebackAttempt

type MetadataWritebackAttempt struct {
	AssetID     int64
	MetadataRev int64
	StoragePath string
	TempPath    string
	Hash        []byte
	Size        int64
}

func LoadMetadataWritebackAttempt

func LoadMetadataWritebackAttempt(queryer Queryer, assetID int64) (MetadataWritebackAttempt, bool, error)

type MetadataWritebackAttemptRow

type MetadataWritebackAttemptRow struct {
	MetadataWritebackAttempt
	CurrentStoragePath string
}

func ListMetadataWritebackAttempts

func ListMetadataWritebackAttempts(queryer Queryer) ([]MetadataWritebackAttemptRow, error)

type MetadataWritebackCounts

type MetadataWritebackCounts struct {
	Dirty  int
	Failed int
}

MetadataWritebackCounts summarizes the pending write-back backlog. Failed is the dirty subset with a recorded last error.

func CountDirtyMetadataWritebackAssets

func CountDirtyMetadataWritebackAssets(queryer Queryer, scope VisibilityScope) (MetadataWritebackCounts, error)

CountDirtyMetadataWritebackAssets counts writable live assets whose file metadata is behind the current book metadata.

type MetadataWritebackSnapshot

type MetadataWritebackSnapshot struct {
	BookID       int64
	MetadataRev  int64
	CoverVersion int
	UpdatedAt    int64
	Metadata     bookmeta.Metadata
}

func LoadMetadataWritebackSnapshot

func LoadMetadataWritebackSnapshot(queryer Queryer, assetID int64) (MetadataWritebackSnapshot, error)

LoadMetadataWritebackSnapshot combines shared book fields with this asset's page count. Sibling formats can have different counts at the same book revision.

type OPDSPublicationRow

type OPDSPublicationRow struct {
	ID            int64
	Title         string
	Description   sql.NullString
	Publisher     sql.NullString
	PublishedDate sql.NullString
	Language      sql.NullString
	Identifiers   sql.NullString
	CoverVersion  int
	UpdatedAt     int64
}

func GetOPDSPublication

func GetOPDSPublication(queryer Queryer, scope VisibilityScope, bookID int64) (OPDSPublicationRow, error)

func ListManualShelfOPDSPublications

func ListManualShelfOPDSPublications(queryer Queryer, scope VisibilityScope, shelfID int64, limit, offset int) ([]OPDSPublicationRow, error)

ListManualShelfOPDSPublications returns the downloadable books on one manual shelf in its explicit shelf order. The caller owns shelf visibility; this query independently intersects the books with the user's content scope so a personal shelf can never widen a shelf-scoped reader's library.

func ListOPDSPublications

func ListOPDSPublications(queryer Queryer, scope VisibilityScope, limit, offset int) ([]OPDSPublicationRow, error)

ListOPDSPublications is the narrow read model for OPDS acquisition feeds. It only returns live books that have at least one asset, because an OPDS publication entry without an acquisition link is not useful to external readers.

func ListRecentOPDSPublications

func ListRecentOPDSPublications(queryer Queryer, scope VisibilityScope, limit, offset int) ([]OPDSPublicationRow, error)

ListRecentOPDSPublications is ListOPDSPublications ordered newest-first, for the "Recently added" navigation entry.

func ListTagOPDSPublications

func ListTagOPDSPublications(queryer Queryer, scope VisibilityScope, name string, limit, offset int) ([]OPDSPublicationRow, error)

func SearchOPDSPublications

func SearchOPDSPublications(queryer Queryer, scope VisibilityScope, userID int64, q string, limit, offset int) ([]OPDSPublicationRow, error)

SearchOPDSPublications applies the same FTS terms and structural/per-user filters as browser search. Filter-only queries (including status:unread) are valid saved shelves; a genuinely empty query still returns no rows.

type PageCountAsset

type PageCountAsset struct {
	AssetID     int64
	StoragePath string
	Format      format.Format
	Hash        []byte
	Size        int64
	PageCount   int
}

func PrimaryPageCountAsset

func PrimaryPageCountAsset(queryer Queryer, scope VisibilityScope, bookID int64) (PageCountAsset, error)

type PrimaryAssetRow

type PrimaryAssetRow struct {
	ID          int64
	BookID      int64
	Title       string
	Extension   string
	Format      format.Format
	CurrentHash []byte
}

func PrimaryAssetForBook

func PrimaryAssetForBook(queryer Queryer, scope VisibilityScope, bookID int64) (PrimaryAssetRow, error)

type Queryer

type Queryer interface {
	Query(query string, args ...any) (*sql.Rows, error)
	QueryRow(query string, args ...any) *sql.Row
}

Queryer reads from the library's reader pool or an existing transaction.

type ReaderPositionWrite

type ReaderPositionWrite struct {
	Revision   int64
	Progress   float64
	Locator    Locator
	DeviceID   string
	DeviceName string
}

ReaderPositionWrite is a reader's observed position. Revision identifies the saved position it was based on; DeviceID identifies the reader.

type ReaderProgress

type ReaderProgress struct {
	// Nil means no reading yet or an explicitly reset position; zero is the beginning.
	Progress      *float64
	ReadingStatus ReadingStatusState
}

func GetReaderProgress

func GetReaderProgress(queryer Queryer, userID, assetID int64) (*ReaderProgress, error)

type ReaderState

type ReaderState struct {
	UserID           int64
	AssetID          int64
	BookID           int64
	Progress         float64
	Locator          Locator
	KOReaderPosition string
	KoboPosition     KoboPosition
	Revision         int64
	DeviceID         string
	DeviceName       string
	UpdatedAt        int64
	// contains filtered or unexported fields
}

func GetReaderState

func GetReaderState(queryer Queryer, userID, assetID int64) (*ReaderState, error)

func (*ReaderState) KOReaderState

func (state *ReaderState) KOReaderState() *KOReaderState

type ReadingActivityCheckpoint

type ReadingActivityCheckpoint struct {
	Segment        int64
	ElapsedMS      int64
	LastActivityMS int64
	Finished       bool
}

ReadingActivityCheckpoint reports times relative to the current segment's start. Counted time from earlier segments stays in the session total.

type ReadingActivityResult

type ReadingActivityResult struct {
	Active    bool  `json:"active"`     // This segment may continue recording time.
	CountedMS int64 `json:"counted_ms"` // Session total, including earlier segments.
}

type ReadingStatusChange

type ReadingStatusChange struct {
	State   ReadingStatusState
	Changed bool
	EventID int64
}

type ReadingStatusSource

type ReadingStatusSource string
const (
	ReadingStatusSourceManual    ReadingStatusSource = "manual"
	ReadingStatusSourceWebReader ReadingStatusSource = "web_reader"
	ReadingStatusSourceKOSync    ReadingStatusSource = "kosync"
	ReadingStatusSourceOPDS      ReadingStatusSource = "opds"
	ReadingStatusSourceKobo      ReadingStatusSource = "kobo"
)

type ReadingStatusState

type ReadingStatusState struct {
	UserID      int64
	BookID      int64
	Status      string
	LastEventID int64
	UpdatedAt   int64
}

func GetReadingStatus

func GetReadingStatus(queryer Queryer, userID int64, bookID int64) (ReadingStatusState, error)

type Rect

type Rect struct {
	X      float64 `json:"x"`
	Y      float64 `json:"y"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

type SearchQueryValidation

type SearchQueryValidation struct {
	Valid bool
	Error string
	// contains filtered or unexported fields
}

func ValidateSearchQuery

func ValidateSearchQuery(q string) SearchQueryValidation

ValidateSearchQuery is the strict entry point used by saved searches. Normal library search is deliberately lenient, but a persisted query must not change meaning because of a missing value or quote.

type SeriesCard

type SeriesCard struct {
	Name          string
	Author        string
	BookCount     int
	FinishedCount int
	CoverBookID   int64
	CoverVersion  int
}

SeriesCard is one tile on the Series page: the series, how many books it holds, how many of them the viewer finished, and the book that stands for the whole series with its cover and author.

func ListSeriesCardsPage

func ListSeriesCardsPage(queryer Queryer, scope VisibilityScope, userID int64, q, afterName string, limit int) ([]SeriesCard, error)

ListSeriesCardsPage returns one keyset page of Series-page tiles. Names and counts come from the same keyset walk as ListSeriesCountsPage; a second query then enriches only that page with its cover book and finished count, so the per-request work stays proportional to the page instead of the library. limit is the positive page size.

type SeriesCount

type SeriesCount struct {
	Name      string
	BookCount int
}

func ListSeriesCountsPage

func ListSeriesCountsPage(queryer Queryer, scope VisibilityScope, q, afterName string, limit int) ([]SeriesCount, error)

ListSeriesCountsPage returns one stable keyset page ordered by series name. q is an optional substring filter used by the edit autocomplete; the Series page passes it empty. afterName is the opaque cursor's decoded key. limit is the positive page size.

type Shelf

type Shelf struct {
	ID         int64
	Name       string
	Kind       ShelfKind
	Query      string
	QueryMatch string
	OwnerID    int64
	Visibility ShelfVisibility
	Position   int
	CreatedAt  int64
	UpdatedAt  int64
}

func GetShelf

func GetShelf(queryer Queryer, shelfID int64, viewerID int64) (*Shelf, error)

GetShelf returns a shelf visible to viewerID. Zero viewerID can only see shared shelves.

func GetShelfForUser

func GetShelfForUser(queryer Queryer, shelfID int64, userID int64) (*Shelf, error)

GetShelfForUser returns a shelf only if it is visible in the user's current library scope. Use GetShelf for low-level owner/shared checks that should not apply content-scope narrowing.

func ListShelves

func ListShelves(queryer Queryer, viewerID int64) ([]Shelf, error)

ListShelves returns shared shelves plus the viewer's personal shelves. With a zero viewerID it returns only shared shelves.

func ListShelvesForUser

func ListShelvesForUser(queryer Queryer, userID int64) ([]Shelf, error)

ListShelvesForUser returns shelves visible in the user's current library scope. Full-scope accounts see shared shelves plus their personal shelves. Shelf-scoped accounts see assigned shared scope shelves plus their personal shelves, so scope-defining shelves are navigable without exposing unrelated shared shelf names.

type ShelfKind

type ShelfKind string
const (
	ShelfManual ShelfKind = "manual"
	ShelfQuery  ShelfKind = "query"
)

type ShelfMembership

type ShelfMembership struct {
	Shelf
	InShelf bool
}

func ListBookShelfMemberships

func ListBookShelfMemberships(queryer Queryer, viewerID int64, bookID int64) ([]ShelfMembership, error)

ListBookShelfMemberships returns visible manual shelves and whether the book is currently assigned to each. Query shelves are omitted because they cannot be hand-edited.

type ShelfVisibility

type ShelfVisibility string
const (
	ShelfPersonal ShelfVisibility = "personal"
	ShelfShared   ShelfVisibility = "shared"
)

type Tag

type Tag struct {
	ID   int64   `json:"id"`
	Kind TagKind `json:"kind"`
	Name string  `json:"name"`
}

Tag identifies a current dictionary entry independently of loaded list pages.

func GetTag

func GetTag(queryer Queryer, id int64) (Tag, error)

func RenameOrMergeTag

func RenameOrMergeTag(tx *Tx, tagID int64, newName string) ([]int64, Tag, error)

RenameOrMergeTag moves the whole branch, including trashed books. Overlapping branches merge node by node, keeping the first position on each book.

type TagKind

type TagKind string
const (
	TagKindTag   TagKind = "tag"
	TagKindGenre TagKind = "genre"
)

type TagListOptions

type TagListOptions struct {
	Kind       TagKind
	Query      string
	ParentName string
	Sort       TagSort
	AfterName  string
	AfterCount int
	Limit      int
}

type TagRow

type TagRow struct {
	ID          int64
	Name        string
	Key         string
	BookCount   int
	HasChildren bool
}

func ListTagCountsPage

func ListTagCountsPage(queryer Queryer, scope VisibilityScope, opts TagListOptions) ([]TagRow, error)

type TagSort

type TagSort string
const (
	TagSortName  TagSort = "name"
	TagSortBooks TagSort = "books"
)

type TrashedBookRow

type TrashedBookRow struct {
	BookSummaryRow
	DeletedAt     int64
	DeletedByName string
}

TrashedBookRow is a trashed book for the trash listing: the same summary fields the library grid renders, plus when it was trashed and the display name of whoever trashed it (empty if that user has since been removed).

func ListTrashedBooks

func ListTrashedBooks(queryer Queryer, scope VisibilityScope) ([]TrashedBookRow, error)

ListTrashedBooks returns the soft-deleted books, most-recently-trashed first.

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx owns the writer connection until commit, rollback, or caller cancellation. Its statements inherit the context passed to BeginWrite.

func (*Tx) Commit

func (tx *Tx) Commit() error

func (*Tx) Exec

func (tx *Tx) Exec(query string, args ...any) (sql.Result, error)

func (*Tx) Prepare

func (tx *Tx) Prepare(query string) (*sql.Stmt, error)

Prepare uses the transaction's context to prepare a statement. The returned sql.Stmt still needs an explicit context when executed (e.g. ExecContext).

func (*Tx) Query

func (tx *Tx) Query(query string, args ...any) (*sql.Rows, error)

func (*Tx) QueryRow

func (tx *Tx) QueryRow(query string, args ...any) *sql.Row

func (*Tx) Rollback

func (tx *Tx) Rollback() error

type User

type User struct {
	ID           int64
	Username     string
	PasswordHash string
	Role         string
	ContentScope string
	CreatedAt    int64
	UpdatedAt    int64
}

User is an authentication identity. Library content is shared across all users; only per-user state references the user id. password_hash is a bcrypt hash and is never exposed in any DTO or API response.

func Authenticate

func Authenticate(queryer Queryer, username, password string) (*User, error)

Authenticate verifies a username/password pair and returns the matching user. It returns (nil, nil) on any mismatch (unknown user or wrong password) so both yield the same "invalid credentials" response. The responses are identical; the timings are not, because an unknown username returns before bcrypt runs. That enumeration oracle is accepted deliberately for a household-sized user list: usernames are not treated as secrets, while a dummy bcrypt comparison would add CPU cost to every unknown-user attempt without protecting passwords.

func GetUserByID

func GetUserByID(queryer Queryer, userID int64) (*User, error)

GetUserByID looks an account up by id. A missing user returns (nil, nil).

func GetUserByUsername

func GetUserByUsername(queryer Queryer, username string) (*User, error)

GetUserByUsername looks an account up by its (normalized) username. A missing user returns (nil, nil) so callers can distinguish "not found" from an error.

func ListUsers

func ListUsers(queryer Queryer) ([]User, error)

ListUsers returns all accounts ordered by username (admin screens / CLI).

type UserAccess

type UserAccess struct {
	Role          string
	ContentScope  string
	ShelfIDs      []int64
	ShelfViewerID int64
}

UserAccess describes an account's catalog permissions. ShelfViewerID is the curator whose visible personal shelves may be newly selected for ShelfIDs; it is validation context and is not persisted on the target account.

type UserSettings

type UserSettings struct {
	UserID              int64
	Theme               string
	ShowContinueReading bool
	TimeZone            string // Empty means unset; explicit UTC is a saved choice.
	ReaderFlow          string
	ReaderStyle         string
	ReaderFontSize      int
	ReaderColumnWidth   int
	ReaderLineHeight    float64
	UpdatedAt           int64
}

func GetUserSettings

func GetUserSettings(queryer Queryer, userID int64) (*UserSettings, error)

type UserSettingsPatch

type UserSettingsPatch struct {
	Theme               *string
	ShowContinueReading *bool
	TimeZone            *string
	ReaderFlow          *string
	ReaderStyle         *string
	ReaderFontSize      *int
	ReaderColumnWidth   *int
	ReaderLineHeight    *float64
	InitializeTimeZone  bool // Set TimeZone only if no zone is saved yet.
}

type VisibilityScope

type VisibilityScope struct {
	UserID       int64
	ContentScope string
}

VisibilityScope narrows content queries to what one account may see. Authorization is two separate primitives composed with AND — deliberately no single authorize(user, action, book) entry point:

  • capability ("may this user perform action X?") — a minimum-role check, declared per route in web/server.go's route table;
  • visibility ("may this user see book B?") — this scope, ANDed into every content query unconditionally: lists, search, authors, series, tags, OPDS, covers, downloads, reader entry points, sequence navigation.

Contract: a scoped account sees the scoped catalog as its whole library — direct access to an out-of-scope book or asset is a 404, exactly like content that doesn't exist. Access is book-centric (asset resolves to its book). Enforcement covers every authenticated entry point: browser sessions, basic auth, app passwords and device protocols. An empty scope is valid and fail-closed: the account sees an empty library, not an error.

func FullVisibilityScope

func FullVisibilityScope() VisibilityScope

func VisibilityScopeForUser

func VisibilityScopeForUser(queryer Queryer, userID int64) (VisibilityScope, error)

func (VisibilityScope) AppendBookWhere

func (s VisibilityScope) AppendBookWhere(where, bookIDExpr string, args ...any) (string, []any)

func (VisibilityScope) BookWhere

func (s VisibilityScope) BookWhere(bookIDExpr string) (string, []any)

BookWhere returns a predicate restricting bookIDExpr to the scope. A shelf counts as a scope source when it is shared, or personal but owned by someone *else* (a curator's hidden allowlist) — the owner_id <> user_id half excludes the scoped reader's own personal shelves, which is what keeps "nothing a reader does can widen their scope" true: readers organize already-visible books, only curators grant access.

Eligible query shelves are access boundaries, so "list all matching books" and "does book B match" must stay one predicate (the same MATCH against the same non-empty query_match here and in visibleBooksCTE). New books matching one become visible with no review: dynamic by design, accepted for the household trust model. Relational no: filters and per-user status: filters are never eligible because query_match cannot represent their full meaning. If the grammar ever grows OR/NOT/grouping, re-audit scope eligibility before allowing those expressions at an authorization boundary.

func (VisibilityScope) IsFull

func (s VisibilityScope) IsFull() bool

type WriterLease

type WriterLease struct {
	// contains filtered or unexported fields
}

func AcquireWriterLease

func AcquireWriterLease(ctx context.Context, database *DB, owner string, force bool) (*WriterLease, error)

func (*WriterLease) Release

func (l *WriterLease) Release(ctx context.Context) error

func (*WriterLease) Renew

func (l *WriterLease) Renew(ctx context.Context) error

func (*WriterLease) RunHeartbeat

func (l *WriterLease) RunHeartbeat(ctx context.Context, interval time.Duration) error

RunHeartbeat renews the lease until ctx is canceled or renewal fails. It returns nil on cancellation.

type WriterLeaseHeldError

type WriterLeaseHeldError struct {
	Owner string
}

func (WriterLeaseHeldError) Error

func (e WriterLeaseHeldError) Error() string

func (WriterLeaseHeldError) Unwrap

func (e WriterLeaseHeldError) Unwrap() error

Jump to

Keyboard shortcuts

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