- Python 38.7%
- JavaScript 26%
- Kotlin 18.5%
- Shell 8%
- CSS 4.9%
- Other 3.9%
The photo is resized to 1600 px and stripped of all metadata, including the phone's GPS position. The Gradle wrapper keeps its Apache-2.0 license, listed in THIRD_PARTY_NOTICES.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|---|---|---|
| android | ||
| cli | ||
| code | ||
| docs | ||
| ibom | ||
| server | ||
| .gitignore | ||
| LICENSE | ||
| README.md | ||
| requirements.txt | ||
| THIRD_PARTY_NOTICES.md | ||
PartDB
Shelf inventory for electronic components, backed by PostgreSQL.
Every reel or bag you own occupies a slot — a (shelf, position) pair. PartDB decides where a
new package goes, tells you where to put it, and remembers where everything is. When you build a
board it tells you which shelf to open, and on the way back it decrements the count for you.
Parts are keyed by their LCSC part number (the C number, e.g. C5360459), and part metadata
is fetched from LCSC on demand.
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Android app │ │ web console │ │ partdb CLI │
│ scan a bag │ │ keyboard │ │ terminal │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ bearer token │ cookie │ bearer token
└──────────────────┼──────────────────┘
▼
┌───────────┐
│ nginx │ :80 production · :8080 test
└─────┬─────┘
┌──────────────┴──────────────┐
▼ ▼
┌───────────────┐ ┌───────────────┐
│ PartDB API │ │ PartDB API │
│ production │ │ test │
│ :8100 │ │ :8101 │
└───────┬───────┘ └───────┬───────┘
│ unix socket │
▼ ▼
┌───────────┐ ┌─────────────┐
│ partdb │ ──── copied ──▶ │ partdb_test │
└───────────┘ every deploy └─────────────┘
Slot allocation lives in the API, so no two clients can disagree about where a package went. The two environments run identical code against separate databases; test is overwritten with a copy of production on every deployment, so it is always realistic and never precious.
Contents
| Path | What it is |
|---|---|
server/ |
FastAPI service — the only thing that touches the database |
server/openrc/, server/systemd/ |
Service files for Alpine and Debian |
server/nginx/ |
Reverse proxy publishing both environments |
server/setup-container.sh |
One-time container provisioning, re-runnable |
server/deploy.sh |
Deploy from a checkout — run this one |
server/deploy-remote.sh |
The container side of a deployment |
server/sync-test-from-prod.sh |
Replaces the test database with a copy of production |
android/ |
Android app for scanning LCSC package labels |
cli/ |
partdb, a terminal client that talks to the API |
code/ |
The original direct-to-database CLI. Superseded — see Legacy |
ibom/ |
Project BOM exports, read by BOM mode |
docs/ |
Images for this README |
How it works
Slots and shelves
A shelf has a fixed capacity and a package size class:
| Size | Meaning |
|---|---|
S |
Small — cut tape, small bags |
M |
Medium — standard reels |
L |
Large — big reels, bulky components |
Slot allocation
When a package is added, PartDB picks its slot in this order:
- Reuse a freed slot. Removing a package records its slot in
empty-shelves. The lowest matching one is reused first, so gaps get filled rather than accumulating. - Extend the first shelf with room. Otherwise the first non-full shelf of that size hands out
PACKAGES-NUM + 1.
Both steps take SELECT … FOR UPDATE on the row they consume, so two people adding at the same
moment cannot be handed the same slot. Allocation and insert share one transaction — a failure
can't leave a consumed slot with no package in it.
The take-out / return cycle
A package physically off the shelf is marked FILLED = FALSE. That's deliberate: you can pull
several packages onto the bench, build the board, and reconcile quantities afterwards.
take out ──► FILLED = FALSE (on your bench; quantity unchanged)
│
│ "how many did you use?"
▼
return ──► FILLED = TRUE, QUANTITY -= used
│
│ if it hits 0, optionally
▼
remove ──► row deleted, slot queued for reuse
Every transition writes a part_log row with timestamps and before/after counts.
Setting up the server
The API and PostgreSQL live in one Incus container and talk over a unix socket, so no database password exists anywhere on disk.
Alpine 3.24 is the recommended base. The usual reason to reach for Debian on a Python service —
musl having no binary wheels, so everything compiles — no longer applies: every C extension in this
stack (psycopg2-binary, uvloop, httptools, pydantic-core) ships musllinux wheels, and the
whole thing installs with no compiler present. Alpine 3.23+ also carries postgresql18 18.6, the
same version PGDG gives Debian.
Measured, same workload, both idle:
| Alpine 3.24 | Debian 13 | |
|---|---|---|
| PostgreSQL | 18.6 | 18.6 (PGDG) |
| Rootfs with the full stack | 226 MB | 539 MB |
| Idle RSS | ~50 MB | ~72 MB |
| Init | OpenRC | systemd |
Service files for both are in server/openrc/ and server/systemd/. The Debian route is written
out at the end of this section.
Both environments live in that one container. nginx is the only thing bound to a LAN-facing port; each uvicorn listens on loopback:
| URL | Environment | Database | Behind it |
|---|---|---|---|
http://<host>/ |
production | partdb |
127.0.0.1:8100 |
http://<host>:8080/ |
test | partdb_test |
127.0.0.1:8101 |
Two ports, one meaning each. A bare address is production; :8080 is test. Nothing else answers,
so a client pointed at the wrong port fails loudly instead of quietly reaching the real inventory.
1. Container
incus launch images:alpine/3.24 partdb -c limits.memory=1GiB -c limits.cpu=2
incus exec partdb -- sh
2. PostgreSQL
apk add postgresql18 postgresql18-contrib python3 py3-pip
mkdir -p /run/postgresql /var/lib/postgresql/18/data
chown postgres:postgres /run/postgresql /var/lib/postgresql/18/data
su postgres -s /bin/sh -c "initdb -D /var/lib/postgresql/18/data"
rc-update add postgresql default && rc-service postgresql start
postgresql18-contrib supplies pg_trgm, which the schema uses for fast substring search. If your
part descriptions need non-English collation, add icu-data-full — not needed for the default C
collation.
That is the whole manual part. Everything below is scripted.
3. Provision and deploy
From a checkout on your own machine, not in the container:
server/deploy.sh --setup --host root@192.168.1.50
--setup runs server/setup-container.sh on the container first, which is idempotent — re-run it
any time you change a service file or the nginx config. It installs nginx, creates the partdb
role and both databases, writes /etc/partdb/prod.env and /etc/partdb/test.env, installs the
OpenRC services, and adds everything to the default runlevel.
A fresh partdb database is created from schema.sql and seed-shelves.sql. The second one
matters: a database with tables but no shelves has nowhere to put anything, and every add fails
with "No shelf of size S has room left". Edit the counts in seed-shelves.sql to match your real
storage before the first run. Restoring an existing dump brings your shelves with it.
Setup keeps an existing token if one is already on the container, so re-running it never invalidates clients you have already paired. Both environments share one token — see Test and production.
After that, every subsequent deployment is just:
server/deploy.sh
Check it:
curl http://192.168.1.50/api/health
# {"status":"ok","database":true,"version":"2.0.0","environment":"prod"}
curl http://192.168.1.50:8080/api/health
# {"status":"ok","database":true,"version":"2.0.0","environment":"test"}
/api/health needs no token, so monitoring can poll it. Find the container's LAN address with
incus list partdb — that alone is what goes into the phone app.
Doing it by hand
The scripts are short, and between them setup-container.sh and deploy-remote.sh are the
authoritative description of the layout they build:
/opt/partdb/prod/app production code /etc/partdb/prod.env
/opt/partdb/prod/venv /etc/conf.d/partdb-api
/opt/partdb/test/app test code /etc/partdb/test.env
/opt/partdb/test/venv /etc/conf.d/partdb-api-test
/opt/partdb/staging what deploy.sh uploads
/opt/partdb/bin backup and sync scripts
/etc/init.d/partdb-api-test is a symlink to /etc/init.d/partdb-api. OpenRC sources
/etc/conf.d/$RC_SVCNAME before running the script, so one service definition serves both
instances and each picks up its own root directory, port and env file.
On Debian instead
If you would rather have systemd and a 5-year support window, Debian 13 runs the same stack. Note
that setup-container.sh is Alpine-only — it calls apk and rc-update — so on Debian the
provisioning is manual and the systemd units in server/systemd/ cover a single environment, not
the prod/test split. The differences are PostgreSQL coming from the PGDG repo, and systemd units in
place of OpenRC:
incus launch images:debian/13 partdb -c limits.memory=2GiB -c limits.cpu=2
apt update && apt install -y curl ca-certificates
install -d /usr/share/postgresql-common/pgdg
curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc \
https://www.postgresql.org/media/keys/ACCC4CF8.asc
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] \
https://apt.postgresql.org/pub/repos/apt trixie-pgdg main" \
> /etc/apt/sources.list.d/pgdg.list
apt update && apt install -y postgresql-18 python3-venv git
# create the role, database and schema as in step 2, then:
cp /opt/partdb/app/server/systemd/*.service /opt/partdb/app/server/systemd/*.timer \
/etc/systemd/system/
systemctl daemon-reload
systemctl enable --now partdb-api.service partdb-backup.timer
Backups
Backups run nightly, write a compressed pg_dump to /var/backups/partdb, and keep 14 days. The
script refuses to prune old dumps unless the new one is a plausible size.
Only production is backed up. partdb_test is replaced wholesale on every deployment, so there is
nothing there worth keeping.
On Alpine that is /etc/periodic/daily/partdb-backup, run by busybox crond, calling
/opt/partdb/bin/partdb-backup.sh — which every deployment refreshes, so cron never ends up
running a stale copy. On Debian it is partdb-backup.timer at 03:30, with catch-up enabled since
laptops are usually asleep then.
A deployment also takes its own dump immediately before touching production, so there is always a restore point from seconds before any change.
Put that directory on a device that outlives the container:
incus config device add partdb backups disk \
source=/srv/backups/partdb path=/var/backups/partdb
Restore with:
pg_restore --dbname=partdb --clean --if-exists /var/backups/partdb/partdb-<stamp>.dump
Test and production
Two identical stacks, separate databases. The point is a place to scan real barcodes, run real commands and break real things without touching the inventory you actually rely on.
| production | test | |
|---|---|---|
| URL | http://192.168.1.50/ |
http://192.168.1.50:8080/ |
| Database | partdb |
partdb_test |
| Data | the real inventory | a copy of production, refreshed every deployment |
| Backed up | nightly | never — it is disposable by design |
Telling them apart
Writing to the wrong system is the only new way this setup can hurt you, so every client says which one it is talking to:
- Web console — an orange banner across the top reading "test instance — this is not the real
inventory", an orange outline around the page, and the browser tab titled
PartDB [test]. - CLI — a warning line above the output:
── TEST ── http://192.168.1.50:8080 is not the real inventory. - Anything else —
/api/healthreports"environment": "prod"or"test".
Production shows none of this. No banner means the real thing.
What a deployment does
server/deploy.sh uploads your working tree — including uncommitted changes — to
/opt/partdb/staging on the container, then promotes it:
1. staging ──▶ /opt/partdb/test/app test gets the new code first
2. partdb ──▶ partdb_test test data replaced with a fresh copy of production
3. migrate partdb_test, restart, health check
└── if test does not come up healthy, the deployment stops here
and production is never touched
4. dump partdb a restore point from seconds ago
5. staging ──▶ /opt/partdb/prod/app
6. migrate partdb, restart, health check
Test being first is the whole point: a deployment that is going to break something breaks the disposable copy, and stops.
server/deploy.sh # test, then production
server/deploy.sh --test-only # test only; production stays on its current version
server/deploy.sh --no-sync # keep whatever is in the test database right now
server/deploy.sh --setup # provision the container first (idempotent)
server/deploy.sh --host root@10.0.0.5
--test-only is what you want while iterating: push a change, poke at it on :8080, repeat, and
promote when it holds up.
Anything written to test is lost on the next deployment. That is not a caveat, it is the
feature — test is always a faithful copy of production rather than a database that has drifted into
a state nothing else ever reaches. Use --no-sync when you want to keep a scenario across a code
change.
Refreshing test on its own
Without deploying anything:
ssh root@192.168.1.50 /opt/partdb/bin/sync-test-from-prod.sh
Data only ever moves production → test. The script refuses to run if its target does not end in
_test, if source and target are the same, or if the dump comes out implausibly small — it drops a
database, so it would rather fail than guess.
Pointing clients at test
- Phone — Settings, change the server address to
192.168.1.50:8080. Same token. - CLI —
PARTDB_URL=http://192.168.1.50:8080 partdb - Browser —
http://192.168.1.50:8080/
Both environments share one token. The security boundary here is the LAN, not the gap between prod and test, and a second token would mean re-pairing the phone every time you switched it over — friction that would just discourage using test at all.
Changing the wiring
deploy.sh handles code, databases and the scripts in /opt/partdb/bin. It deliberately does not
touch service definitions or the nginx config; after editing anything in server/openrc/ or
server/nginx/, re-run:
server/deploy.sh --setup
Migrating an existing database
server/migrate.sql brings an older PartDB database up to what the API expects. It is idempotent —
running it twice changes nothing the second time.
# 1. Dump the old container
pg_dump -h <old-host> -U postgres -d parts --format=custom -f partdb-old.dump
# 2. Restore into the new one
pg_restore --dbname=partdb --no-owner --no-privileges partdb-old.dump
# 3. Migrate
psql -d partdb -f server/migrate.sql
What the migration does:
- Collapses duplicate
lcsc-datarows. The old Selenium scraper inserted unconditionally, so re-running it stacked up copies — 55 duplicate rows across 41 parts, one part with five. Every duplicate group had an identical payload, so keeping the lowest ID loses nothing. This is also why search used to feel bad: duplicates ate the ten result slots. - Adds
DATASHEETandCATEGORYtolcsc-data, filled in by the metadata fetcher. - Adds the missing indexes.
parts."LCSC-PART"had none at all, so every lookup in the app was a sequential scan. Also adds trigram indexes so live search stays fast.
Afterwards, backfill the new columns:
curl -X POST -H "Authorization: Bearer $PARTDB_TOKEN" \
-H "Content-Type: application/json" -d '{}' \
http://localhost/api/maintenance/fetch-metadata
The web console
Open http://<server>/ and paste the token once; it's exchanged for an HttpOnly cookie.
The test console is the same page on :8080, with an orange banner so you cannot confuse the two.
This replaces the old numbered-menu CLI. It keeps the thing that CLI got right — you can drive the whole inventory without touching the mouse — and fixes the thing it got wrong, which was search.
One box, three modes
Everything starts in the omnibox, which dispatches on what you type:
| You type | What happens |
|---|---|
C5360459 |
That part: metadata, every package, where each one lives |
5360459 |
Same — the C is optional everywhere |
0603 10k |
Search. Every term must match, so terms narrow |
> add C123 |
A command |
Search is the big change. It matches across part name, description, manufacturer and package, requires every term, deduplicates by part number, and puts parts you actually stock first with their quantities inline — so you can see what you have without opening anything.
Keys
| Key | Does |
|---|---|
↑ ↓ |
Move through rows |
Enter |
Open the highlighted row |
t |
Take out the highlighted package |
r |
Return it |
e |
Edit its quantity |
s |
Move it to a shelf of another size |
x |
Remove it and free the slot |
a |
Add a package of the current part |
m |
Fetch this part's metadata from LCSC |
h |
This part's history |
space |
In BOM mode, mark a line done; on the combine list, tick a package |
o |
On the combine list, open the part |
Esc |
Clear, then step back |
The one rule: single-key actions fire only while the omnibox is empty. Otherwise typing
t in the middle of 0603 10k would take a package out mid-word.
You mostly never notice this, because opening any detail view clears the box for you. The footer tells you which keys are live for the current view, and warns you when text in the box has paused them.
Esc is staged so it never strands you:
- Text in the box on a detail view → clears the box, keeps you on the part, shortcuts resume.
- Box already empty → back to the search results you came from, query restored.
- Already at the results → clears everything.
Enter reads the situation rather than always re-submitting: on a part number or a > command it
acts on what you typed, but when search results for the current text are already on screen it opens
the highlighted row.
Any recognised shortcut that can't apply says so instead of doing nothing — pressing t on a
package that's already on the bench tells you to press r.
Commands
| Command | Does |
|---|---|
> add C123 |
Add a package |
> out |
Everything currently on the bench |
> empty |
Packages at zero, with a bulk purge |
> shelves |
Shelf occupancy |
> log |
Recent activity |
> meta |
Fetch all missing metadata from LCSC |
> dedupe |
Collapse duplicate metadata rows |
> combine |
Combine packages of the same part into one slot |
> bom |
Walk a project BOM from ibom/ |
> help |
The cheat sheet |
Combining duplicates
Adding a second bag of a part you already stock takes a second slot, by design — two physical bags
need two places to live. Over time that spreads one part across a lot of slots. > combine is the
cleanup pass for when you have physically tipped those bags into one.
It lists every part held in more than one package, most-split first, so the worst offenders are at the top — the part eating twelve slots to hold thirty-five components is the one worth walking to the shelf for. Each part shows all of its locations with quantities.
Two controls per row, because they answer two different questions:
- checkbox — this bag went into the pile
- radio — and the pile ended up in this slot
The radio implies its own checkbox, so picking a destination ticks it. The destination defaults to the fullest package, which is the one you would physically tip the others into. Combine is disabled until at least one other package is ticked.
Keyboard: ↑ ↓ to move, space to tick, t to set the destination, Enter to combine, o to
open the part.
On confirm, the destination keeps its slot and absorbs every ticked quantity; the other records are
deleted and their slots go back on the reuse queue. There is no undo. The audit log records it
both ways — a MERGE entry on the destination naming every slot folded in, and a REMOVE on each
source naming where its stock went — so > log can always tell you where something came from.
A package that is on the bench blocks its group: its quantity has not been reconciled by a return yet, so folding it in now would bake in a number that is about to change. Return it first.
After combining: the size no longer fits
Four bags tipped into one rarely fit the slot the smallest of them was standing in, so the combine step is followed by "Does it still fit?" — pick a package size and PartDB frees the old slot, allocates one of the new size, and tells you where to put it. Close the prompt to leave it alone.
The same move is available any time from the part view: highlight a package and press s, or use
the Size button on the row. Package sizes are shown on every package row now, so you can see
what a part is sitting in before deciding.
The new slot is taken before the old one is released. If no shelf of the requested size has room the whole thing rolls back with "No shelf of size L has room left" and the package has not moved — rather than freeing its slot and leaving it homeless.
BOM mode
> bom lists the CSVs in ibom/ and walks one. Each line is joined against live stock, so you see
what's short before you start pulling. space marks a line done. The CSV needs an LCSC Part and
a Qty column; DNP, Value, Footprint and Designator are used when present.
The Android app
Scan the QR on an LCSC bag, adjust the quantity, pick a size, and it tells you which shelf to open.
Building
Needs an Android SDK with platform 34, and a JDK between 17 and 21. Gradle 8.11 cannot parse a
JDK 24+ version string and fails with a bare IllegalArgumentException: 26.0.2, which looks like
nothing at all — if your system JDK is newer, point the build at an older one:
cd android
echo "sdk.dir=$HOME/Android/Sdk" > local.properties
JAVA_HOME=/usr/lib/jvm/java-21-openjdk ./gradlew :app:assembleDebug
adb install app/build/outputs/apk/debug/app-debug.apk
The APK is ~42 MB because ML Kit's barcode model is bundled rather than downloaded — scanning works with no Play Services and no internet beyond your LAN.
First run
Open settings (gear, top right) and enter:
- Server address —
192.168.1.50for production,192.168.1.50:8080for test. Thehttp://is filled in if you omit it; a bare address means port 80, which is production. - API token — the
PARTDB_TOKENfrom/etc/partdb/prod.envon the container. Both environments share it, so switching the address is all it takes to move between them.
Test confirms it can reach the server and reports what's in the database.
Scanning
LCSC labels carry a QR code like this:
{pbn:PICK2408060005,on:GB2408060143,pc:C5360459,pm:WAFER-XH2.54-7PJK,
qty:20,mc:,cc:1,pdi:123387709,hp:null,wc:ZH}
It looks like JSON but isn't — bare keys, bare values, nothing quoted — so a JSON parser rejects
it. PartDB reads pc (the LCSC number), pm (manufacturer part number) and qty.
The phone parses the code itself, so the form fills in the instant the camera reads it, then the server call adds what it knows. That means:
- Quantity is pre-filled from the label's
qty. Usually you don't touch it.−/+step by one, chips step by ±10 and ±100, or tap the field and type. - Size is pre-selected when every package of that part already lives on one size of shelf.
- Existing stock is shown if you already hold this part.
Then Add to shelf, and the slot fills the screen — big enough to read at arm's length while holding a component in the other hand.
If a label is scuffed or a bag has been relabelled, type the C-number into the field under the viewfinder instead.
Duplicates
Scanning a part you already hold shows what's in stock and still adds to a new slot by default, so the number of rows keeps matching the number of physical bags. If it really is the same bag being topped up, Merge here on any listed package adds to that one instead.
The terminal client
cli/partdb talks to the API, so it can't drift from the other clients.
export PARTDB_URL=http://192.168.1.50 # production
# export PARTDB_URL=http://192.168.1.50:8080 # test
export PARTDB_TOKEN=...
# or put both lines in ~/.config/partdb/config
./cli/partdb # interactive menu
./cli/partdb C5360459 # look up a part
./cli/partdb search 0603 10k
./cli/partdb add C5360459 20 S
./cli/partdb out # what's on the bench
./cli/partdb stats
API
Interactive docs at http://<server>/docs.
Auth is one shared bearer token — Authorization: Bearer <token>, or the cookie the web console
sets. /api/health is the only unauthenticated route.
| Method | Path | Does |
|---|---|---|
GET |
/api/health |
Liveness; no token needed |
GET |
/api/stats |
Totals and things needing attention |
GET |
/api/search?q= |
Search; every term must match |
GET |
/api/parts/{lcsc} |
A part, its metadata and packages |
POST |
/api/packages |
Add a package; returns the slot |
POST |
/api/packages/{id}/take-out |
Mark as off the shelf |
POST |
/api/packages/{id}/return |
Return and subtract what was used |
POST |
/api/packages/{id}/top-up |
Add to an existing package |
PATCH |
/api/packages/{id}/quantity |
Correct a count |
POST |
/api/packages/{id}/move |
Move to a shelf of another size; returns the new slot |
DELETE |
/api/packages/{id} |
Delete and free the slot |
GET |
/api/duplicates?limit= |
Parts split across slots, most-split first |
POST |
/api/packages/merge |
Combine packages into one slot |
GET |
/api/checked-out |
Packages on the bench |
GET |
/api/shelves |
Shelf occupancy |
GET |
/api/log?lcsc=&limit= |
Audit trail |
POST |
/api/scan |
Parse an LCSC QR, enriched with stock |
GET |
/api/lcsc/{lcsc} |
Look up on LCSC without storing |
POST |
/api/maintenance/fetch-metadata |
Cache metadata from LCSC |
POST |
/api/maintenance/purge-empty |
Delete packages at zero |
POST |
/api/maintenance/dedupe-metadata |
Collapse duplicate metadata rows |
GET |
/api/boms, /api/boms/{name} |
Project BOMs, joined against stock |
LCSC metadata
LCSC reworked their site and the old Selenium scraper — which drove Firefox through a search page for every part — no longer works against it.
The product page is a Next.js app, so it ships its own data as JSON in a __NEXT_DATA__ script
tag, and the part number addresses it directly:
https://www.lcsc.com/product-detail/C81080.html
A plain HTTP GET and a JSON parse gets everything the scraper used to dig out of the DOM, plus a
datasheet URL and a category. No browser, no driver, no headless display — it runs inside the
container. Parts LCSC doesn't know return a clean 404 and are stored as - so they aren't retried
forever.
Fetching upserts rather than inserts, so re-running it can never pile up duplicates the way the old scraper did.
# everything missing
curl -X POST -H "Authorization: Bearer $PARTDB_TOKEN" \
-H "Content-Type: application/json" -d '{}' \
http://localhost/api/maintenance/fetch-metadata
Requests are paced ~0.4 s apart. This walks LCSC's public site; hammering it is rude and a good way to get rate limited.
It shows up in the log
Every lookup writes a METADATA entry, so > log — and a part's own history under h — answer
"when did this metadata come from, and where did it go wrong":
METADATA C118141 Cached from LCSC: K2-1107ST-A4DW-06 · Korean Hroparts Elec
METADATA C123456 Refreshed from LCSC: RC0603JR-0710KL · YAGEO
METADATA C999999 LCSC has no page for this part
METADATA C111222 LCSC lookup failed: rate limited by LCSC
Cached means there was nothing there before, Refreshed means it replaced an existing row.
Failures are logged too: a batch that quietly gave up on a dozen parts otherwise looks exactly like
one that had nothing to do. These entries carry no shelf and no quantity — they change what we know
about a part, not where it is or how much of it there is.
GET /api/lcsc/{lcsc} is the exception. It looks a part up without storing anything, so it logs
nothing either.
What the API can and cannot do
There is no endpoint that accepts SQL, a query, a table name, or a column name. The service exposes eleven named write operations and nothing else:
add_package · top_up_package · take_out · return_package · set_quantity ·
move_package · remove_package · merge_packages · purge_empty_packages ·
upsert_metadata · deduplicate_metadata
Anything a client wants to change has to map onto one of those. The layering enforces it:
| Layer | Holds |
|---|---|
partdb/api.py |
Routes and auth. Zero SQL statements. |
partdb/service.py |
The named operations. The only module with SQL. |
partdb/db.py |
Pool and transactions. No business logic. |
Values reach the database only as bound parameters. The one place SQL is assembled at all is
search(), and what it interpolates is a fixed condition template repeated once per search term —
the terms themselves are bound. Four layers stand in front of that:
- Pydantic rejects wrong types before a handler runs; package size is
Literal["S","M","L"]. parse_lcsc_number()regex-validates every LCSC number, so a non-numeric one 404s before any query is built.- Bound parameters throughout — psycopg2 does the escaping.
- Path names for BOMs are rejected if they contain a separator.
Worth knowing about the deployment, though: the partdb role owns its tables, so it has the rights
to alter them. That is fine for a single-purpose container, but it does mean the token is the only
thing between the LAN and your data. Keep it out of shell history, and if the API ever leaves the
LAN, put TLS in front of it first.
Database schema
Six tables. Most identifiers are quoted, upper-case and hyphenated — carried over from the original
schema so existing data restores cleanly. Nothing outside server/partdb/service.py sees them; the
API is snake_case throughout.
parts — one row per physical package
| Column | Type | Notes |
|---|---|---|
ID |
serial PK | |
SHELF-ID |
int | which shelf |
SHELF-NUM |
int | position within it |
LCSC-PART |
int | LCSC number without the C |
COMMENT |
text | free text, defaults to - |
QUANTITY |
int | components left in this package |
FILLED |
bool | FALSE = checked out |
A part with several packages simply has several rows.
shelves
| Column | Type | Notes |
|---|---|---|
SHELF-ID |
serial PK | |
MAX-PACKAGES |
int | capacity; -1 means unlimited |
PACKAGE-SIZE |
text | S, M or L |
PACKAGES-NUM |
int | highest slot handed out so far |
empty-shelves — freed slots queued for reuse
ID, SHELF-ID, SHELF-NUM.
lcsc-data — metadata cache
ID, LCSC-PART, PART-NAME, DESCRIPTION, MANUFACTURER, PACKAGE, DATASHEET, CATEGORY.
PART-NAME = '-' marks a part LCSC has no page for.
part_log — append-only audit trail
| Column | Type | Notes |
|---|---|---|
ts |
timestamptz | defaults to now() |
action |
text | ADD / TAKE_OUT / RETURN / REMOVE / UPDATE_QTY / MERGE / MOVE / METADATA |
qty_delta |
int | generated: qty_after - qty_before |
note |
text |
Plus lcsc_part, shelf_id, shelf_num, qty_before, qty_after.
-- where did those 200 resistors go
SELECT ts, action, shelf_id, shelf_num, qty_delta, note
FROM part_log WHERE lcsc_part = 10418 ORDER BY ts DESC;
part-data
Manual classification, keyed on LCSC-PART. Present in the schema, not used by the API.
Legacy
code/ is the original CLI, which connects straight to PostgreSQL. It still runs, but it bypasses
the API — so it doesn't get the fixed slot allocation, the transaction safety, or the metadata
fetcher, and its option 8 scraper is broken against the current LCSC site.
cli/partdb replaces it. Once you're happy, code/ can be deleted.
One difference worth knowing if you go back to it: the old slot allocator counted full shelves and used that count as a list index, which picked the wrong shelf whenever a full one sat after a non-full one. The API selects the first shelf with room directly.
Development
Run against a throwaway database rather than the real one:
initdb -D /tmp/pgdata -U partdb --auth=trust
pg_ctl -D /tmp/pgdata -o "-h 127.0.0.1 -p 5433" -l /tmp/pg.log start
createdb -h 127.0.0.1 -p 5433 -U partdb partdb
psql -h 127.0.0.1 -p 5433 -U partdb -d partdb -f server/schema.sql
cd server
DB_HOST=127.0.0.1 DB_PORT=5433 DB_USER=partdb DB_NAME=partdb \
PARTDB_TOKEN=dev-token PARTDB_BOM_DIR=../ibom PARTDB_ENV=dev \
python -m uvicorn partdb.api:app --reload --port 8000
PARTDB_NO_AUTH=1 disables the token for local work. PARTDB_ENV is anything other than prod,
which puts the banner in the web console and the warning in the CLI — worth setting even locally,
so a stray browser tab is never ambiguous.
For anything that needs real data — barcode scanning, the phone app, BOM mode — the container's
test instance on :8080 is the better target. server/deploy.sh --test-only puts your working
tree there against a fresh copy of the real inventory.
The web console is plain HTML, CSS and JavaScript with no build step — edit server/static/ and
reload.
Its behaviour is covered by jsdom tests that load the real page and press real keys:
cd server/tests && npm install && npm test
Worth running after touching static/app.js. They are cheap and they have already caught a render
crash that would have taken the whole view down.
License
MIT — see LICENSE. The Gradle wrapper in android/ is Apache-2.0; see
THIRD_PARTY_NOTICES.md.
