Kodi database writing
Write to Kodi's own library databases without corrupting them or wedging Kodi. Use when an add-on populates MyVideos or MyMusic directly, when library rows are wrong or missing after a sync, when a stored songid points at a different track after a rebuild, or when deciding between JSON-RPC and SQLite for library writes. Covers the echo loop that JSON-RPC writes cause, the free way to make widgets notice a direct write, why Library.HasContent cannot tell you the skin has caught up, the reserved artist row, and song-id reuse.From its SKILL.md
npx -y skills add kontell/kodi-drive --skill kodi-database-writingAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
2 things to look at
- no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
What its file declares
Copied from the file, not written here
The file declares its own license as CC-BY-SA-4.0. That is the author’s claim about this one file, and it is not the same thing as the license GitHub reports for the repository, which is listed with the other numbers below.
SKILL.md
10.8 KB, as published. Nobody here has run it
Writing Kodi's library directly
Some add-ons populate Kodi's own library rather than serving a plugin://
listing. It gives native browsing, widgets and artwork — and it means owning a
schema you do not control.
Read kodi-library-data first for where the
files are and how to read one safely.
Never write the library through JSON-RPC
VideoLibrary.Set* and its relatives raise Kodi announcements. If your add-on
also listens for those announcements to sync back to a server, you have built
an infinite loop:
write → VideoLibrary.OnUpdate → push to server → echo back → write → ...
Direct SQLite writes raise no announcement, which is the only reason such a sync terminates at all. That is not a happy accident to rely on quietly — it is the actual load-bearing property, so write it down where the next person will see it.
Making a direct write visible, for free
Direct writes leave widgets stale, because nothing announced. The obvious fix —
UpdateLibrary(video) — is safe only because plugin paths carry noUpdate=1, so
Kodi skips them and the scan is a no-op that still completes the cycle.
Music has no noUpdate column at all. A bare UpdateLibrary(music) therefore
walks the real library — roughly 21,000 remote probes in one measured case — and
overlapping music scans have crashed Kodi outright
(CMusicLibraryQueue::StopLibraryScanning, SIGBUS on Android).
The trick that works for both:
kodi-builtin 'UpdateLibrary(music,/does/not/exist)'
Kodi logs "does not exist - skipping scan", finishes in 0 s having probed nothing, and still completes the cycle that invalidates cached containers.
Guard it on Library.IsScanningMusic so two never overlap.
Library.HasContent is not "has the skin caught up"
The scan cycle above refreshes containers that already exist. It cannot help the
empty → populated case: a widget row built while the table was empty stays
empty, because its provider's last fetch returned nothing. Only rebuilding the
windows fixes that, which is what ReloadSkin() is for.
The obvious way to detect that case is to ask whether Kodi thinks the library is empty while your rows exist. That test disarms itself before you can use it.
Library.HasContent(Movies|TVShows|Music|MusicVideos) is a tri-state cache in
xbmc/guilib/guiinfo/LibraryGUIInfo.cpp. Each starts at -1; GetBool runs a
count query and caches the answer only while the value is negative:
case LIBRARY_HAS_MUSIC:
{
if (m_libraryHasMusic < 0)
{ // query
CMusicDatabase db;
if (db.Open())
m_libraryHasMusic = (db.GetSongsCount() > 0) ? 1 : 0;
ResetLibraryBools() puts them back to -1, from five places: the music and
video scanners on scan-finished, GUIWindowMusicBase, CMusicDatabase, and
CProfileManager on profile load.
The trap is what happens between those two facts. A running skin re-evaluates its
visibility conditions continuously, so after any scan resets the bools, the
first re-evaluation after your first row commits caches true — in the middle
of a long write, long before the rebuild that would actually reveal the section.
A check made at the end of the write is then told "Kodi already knows about this
content", declines to reload, and leaves the row empty with a full table under
it. Observed on a first sync that wrote video before music: the music row stayed
blank until an unrelated command happened to rebuild the skin minutes later.
So do not infer "the skin has been rebuilt since this content appeared" from Kodi's bool — it answers a different question. Track it yourself, or reload unconditionally at the point you know the write is finished. An unnecessary reload costs a window teardown; a missed one costs a section that is invisible until something else rebuilds the skin.
Two related notes for anyone reaching for the reload:
- The cost is not what you would guess. Splitting one end-of-write reload into three smaller ones — one per media kind as it lands — measured a lower peak RSS on an ARM box than the single reload did, because one rebuild against a fully populated library re-renders every widget at once while later rebuilds find a warm texture cache.
- Poll for the flag before reloading rather than sleeping a fixed interval, and reload anyway on timeout. Rebuilding against a stale bool at least becomes right on the next reload; not reloading leaves the section hidden until Kodi restarts.
Kodi reserves idArtist 1
Row 1 of the artist table is Kodi's [Missing Tag] blank artist.
An add_artist that computed an id but inserted None let SQLite assign rowid
1 — which happens against an empty table, exactly the state a freshly
repaired music library is in. A real artist then rendered as [Missing], and the
add-on's own mapping pointed at a different row again.
The lesson generalises: Kodi's schema has reserved and sentinel rows. Never let the database assign an id you then need to match.
idSong is reused
song.idSong is INTEGER PRIMARY KEY with no AUTOINCREMENT
(xbmc/music/MusicDatabase.cpp CreateTables, MyMusic83). There is no
sqlite_sequence row for it.
Delete a song and insert another, and SQLite hands the old number out again. An
add-on that persisted songid 12 across a library repair then calls
setDbId(12) on whoever was inserted first into that hole. The stream URL can
still be the saved file; Now Playing and play counts follow the new row. See
kodi-playback-resume.
A rebuild that deletes a contiguous high block and re-inserts in the same order can refill that hole with the same ids. Observed: a secondary music library occupying only high ids came back with those ids unchanged after delete+add. That looks like a clean repair and is a bad reproduction. The failure is a reshuffle — a newest-first walk of a large library into vacated low numbers.
Do not treat a Kodi song id as identity across a wipe. Keep a stable key (a server item id in the URL, or the file path) and look the live row up at use time.
song_artist is how an album's songs are reached
Kodi reaches an album's songs under an artist through song_artist. A song
written with empty ArtistItems gets no row there — so the album appears
empty under the artist while looking completely correct everywhere else.
Measured: 166 songs across 15 of 18 albums. Fall back to AlbumArtists when the
per-song list is empty, which is what Kodi's own scanner does.
Root cause in that case was damaged ID3: smart quotes in TPE1 truncated to the low byte of the UTF-16 code unit. Worth knowing that upstream tag damage presents as a Kodi display bug.
Ordering, atomicity and partial writes
Nest two-database writes so Kodi commits before your own mapping database. The reverse leaves your mapping claiming rows Kodi never got — invisible to every later checksum-gated walk, because your side believes the work is done.
A context manager that commits unconditionally persists half a multi-table write on the exception path. Commit on success only.
A truncated id map is a deletion order, not a smaller answer. len(items) < limit conflates "no more records" with "fewer than I asked for this time", and a
loaded server is entitled to the latter. Page to the server's declared total, and
raise rather than return a partial map.
A non-atomic state file is silent data loss. A truncate-then-rewrite let a
concurrent reader parse half a file, default to an empty whitelist, and skip
items with no exception and no report — while the watermark advanced past them.
Write to a temp file, fsync, then os.replace. And distinguish "missing or
empty" (a fresh install) from "parses but is not an object" (raise loudly).
Schema versions
Gate on the schema version and refuse to write an unrecognised one. Keep
version-keyed constants and .schema fixtures dumped from pristine installs, and
use explicit column lists everywhere so additive schema changes are harmless.
Known versions: Omega ships MyVideos131 and MyMusic83; Piers ships MyVideos146 then MyVideos147, and MyMusic84.
Kodi 22 bumped MyVideos 146→147 mid-beta, and the bump is data-only — the
migration contains no CREATE, ALTER, DROP, INSERT or index statement,
only UPDATEs repairing rar:// escapes and DOS separators. CreateTables and
CreateAnalytics were byte-identical. So a schema-version gate that refuses 147
outright rejects a database it could have handled.
Piers also renumbered the VideoAssetType enum — a value-level change that a
column-level diff will not show you.
What fails silently
- A JSON-RPC library write starts an echo loop that terminates only by accident.
UpdateLibrary(music)walks the whole library and can crash Kodi.- A database-assigned id can collide with a reserved sentinel row.
idSongvalues are reused after delete+insert; a stored songid can name a different track after a rebuild, with no error.- A missing
song_artistrow hides songs under one browse path only. - A partial page reads as a complete, smaller answer.
- A half-written state file parses as an empty one.
Open questions
- Whether the
noUpdateasymmetry between video and music is deliberate has not been established from source; only its effect was measured. - Whether MyVideos147's data-only property holds for the final Kodi 22 release, rather than just the beta, is untested.
- Whether
idMovie/idEpisodeare also plainINTEGER PRIMARY KEY(same reuse) was not checked; onlyidSongon MyMusic83 was.
See also
kodi-library-data— reading, WAL, and which operations destroy add-on rowskodi-announcements— the events a write does or does not raisekodi-performance— why a full scan is far worse on a TV boxkodi-playback-resume— a stalesetDbIdnames the reused row while the path still plays the saved file