All 22 apps

CandyKv

Personal key/value store — one SQLite file per database, glob + fuzzy listing, TTL, binary-safe values

inspired by charmbracelet/skate storekey-valuepersistentdatabase

CandyKv code coverage

candy-kv is a personal key/value store. Each named database is one SQLite file, a key@db suffix routes a key to a database, keys can carry a TTL, values can be binary, and whole databases import and export as JSON or YAML. It ships as a library (Store) and as a bare CLI (candy-kv). The design follows charmbracelet/skate, a Go key/value tool. candy-kv is a native PHP project, not a line-by-line port, and it stores data in SQLite where skate uses BadgerDB.

Install

composer require sugarcraft/candy-kv   # the candy-kv binary lands in vendor/bin/

Requires PHP 8.3 or newer with the sqlite3 and mbstring extensions. A standalone phar is published with the releases. A monorepo checkout runs straight from the tree with php bin/candy-kv after composer install.

Sibling sugarcraft/sugar-core and sugarcraft/sugar-fuzzy requirements track dev-master, so the plain command above only resolves when dev stability is allowed. Pin the package with composer require sugarcraft/candy-kv:@dev, or set minimum-stability to dev with prefer-stable set to true in your consuming manifest. The pin covers the whole sibling closure, so allowing dev for candy-kv alone is not enough.

Quickstart

use SugarCraft\Kv\Store;

$store = new Store();   // SQLite files under $XDG_CONFIG_HOME/skate, else ~/.config/skate

$store->set('user:1', 'Alice');
$store->set('user:2', 'Bob');
echo $store->get('user:1');             // 'Alice'
echo $store->get('missing', 'n/a');     // the fallback: 'n/a'

// A key@db suffix routes to a named database. "\@" spells a literal at-sign.
$store->set('token@passwords', 'ghp_xxxx');
$store->setWithTtl('session', 'abc', 60);   // expires after 60 seconds

foreach ($store->list('user:*') as $entry) {  // character-wise glob, case-sensitive; yields Entry
    echo "{$entry->key} => {$entry->rawValue()}\n";
}
$store->listDatabases();                 // ['default', 'passwords']
$store->pruneExpired();                  // reclaims expired rows in the default database

Constructing a Store touches nothing on disk. Neither the data directory nor any database file is created until the first write, and a read never creates a file.

The CLI in one screen

candy-kv set color blue              # a value with a NUL byte or invalid UTF-8 is stored as binary
candy-kv get color                   # prints the exact stored bytes, with no added newline
candy-kv list 'user-*'               # key<TAB>value rows; a binary value shows a <binary N bytes> placeholder
candy-kv delete 'tmp-*' --dry-run    # reports how many entries would go, writes nothing
candy-kv prune                       # removes expired residue from the default database
candy-kv export json > backup.json
candy-kv import json backup.json     # atomic within one database; a file spanning databases needs --no-atomic

Exit codes: 0 on success, 1 for a miss, no match or a runtime failure, and 2 for usage errors. Unknown flags and commands are refused before anything is written. A data directory that cannot be resolved (see the relative XDG_CONFIG_HOME entry under Troubleshooting) is not caught, so it exits 255. candy-kv --help prints the full flag list.

Concepts

A store is a directory of SQLite files, one per database, named <dir>/<dbname>.db. Unsuffixed keys land in default.db. Store is the facade: it routes each key to a Database through Store::splitKey(), which reads the key@db suffix, and the Database does the row work. Database files are created with mode 0600, and the data directory is 0700.

An Entry is one stored row: the key, its value, the binary flag, the created and modified times, and an optional expiry. An expired row is invisible to readers at once and stays on disk until pruneExpired() or prune reclaims it. Database::raw() is the one reader that still sees an expired row.

A binary value is stored base64-encoded with the binary flag. Entry::rawValue() returns the decoded bytes. The CLI picks binary mode for you when a value contains a NUL byte or invalid UTF-8. --text forces text storage instead: it refuses a value containing a NUL byte outright, and it stores a value that is not valid UTF-8 as text anyway.

Store::list() takes a glob pattern, a database name, a reverse flag and a mode of all, keys or values. Any other mode throws, so a typo cannot quietly yield the wrong shape. Store::fuzzyFilter() ranks the keys of a database against a query with a Smith-Waterman local-alignment matcher, which finds usr1 inside user:1.

Tasks

Keep a backup of one database and restore it

candy-kv export json passwords > passwords.json
candy-kv import json passwords.json --if-exists=skip   # keep what is already there

Export writes the database as a JSON or YAML document, and import reads it back into a database of the same name. --if-exists picks the clobber policy: replace (the default), skip to keep a live row, or fail to refuse and name the key. Import runs in one transaction by default, and an overwriting import reports how much it replaced.

Store a file as a binary value

$store->setFile('logo', '/srv/assets/logo.png');   // binary, read from disk
$store->saveTo('logo', '/tmp/logo-copy.png');     // written back out, mode 0600

Both calls work on binary entries. setFile() returns the stored Entry, and saveTo() returns a bool.

Expire a key and sweep it later

candy-kv set session abc --ttl 300   # expires after five minutes
candy-kv prune --all                # sweep expired rows from every listed database

--ttl must be a positive whole number of seconds, from 1 to 999999999. --ttl 0 is a usage error, not "expire now" and not "forever". Leave --ttl off for an entry that never expires.

Run several transactions on one database

use SugarCraft\Kv\Store;

$store = new Store();
$store->transaction('work', function () use ($store): void {
    // every write in this closure commits together, or none of them does
    $store->set('a@work', 'one');
    $store->set('b@work', 'two');
});

Store::transaction() creates the target database on demand, because a transaction may write. The closure takes no argument. Keep every write on the same database name: a write routed to another database opens its own connection and commits outside the transaction. A transaction aimed at settings throws InvalidArgumentException, and so does a single write to a key routed there.

Import a YAML document across several databases

candy-kv import yaml secrets.yml --no-atomic --max-bytes=0

A file that spans databases cannot run as one transaction, so --no-atomic is needed. --max-bytes=0 lifts the default 256 MiB ceiling on the document, and an oversized document is otherwise refused before its bytes are read.

API reference

The core classes live in SugarCraft\Kv\. Store is the entry point for code, Database is one SQLite file, and Entry is the value a read returns. The CLI commands sit in SugarCraft\Kv\Cli\ (ArgParser, ImportCommand, ExportCommand), the importers, the normalizer, the commit and the report in SugarCraft\Kv\Import\, and the helpers Ttl, Version, SizeCap, PluralChooser and InputPath in SugarCraft\Kv\Support\. The CLI commands and importers sit on top of Store.

ClassMethodDescription
Store__construct(?string $dataDir = null, string $defaultDb = 'default')A store over the data directory. Touches nothing on disk until a write.
Storeset(key, value, bool $binary = false, ?int $ttlSeconds = null), setWithTtl(key, value, int $ttlSeconds)Write a key. key@db routes to a named database.
Storeget(key, fallback = ''), entry(key), suggestionFor(key)A value with a fallback, the full Entry, or the closest existing key for a typo.
Storelist(?pattern, ?dbName, bool $reverse, string $mode = 'all', string $delimiter)A generator of entries, keys or values, in glob order or reverse
StorefuzzyFilter(query, ?dbName)Keys ranked by Smith-Waterman local alignment against a query
Storedelete(key), setFile(key, path), saveTo(key, path)Delete keys by name or glob, store a file as binary, and write a binary value to disk
StorepruneExpired(), pruneDatabase(name)Reclaim expired rows from the default database or a named one
StorelistDatabases(), deleteDatabase(name), isReservedDatabase(name)Database management. settings is reserved.
Storetransaction(dbName, callable $fn)Run a closure against a database inside one transaction
StoredataDir(), defaultDatabase(), splitKey(key, defaultDb), resolveDataDir(), sanitizeForTty(value)Where the data lives, the key@db split, the data-directory resolution, and a value stripped for terminal output
Database__construct(path, name, bool $create = true), get, raw, set, delete, list, countOne SQLite database. raw() also sees expired rows.
DatabasedeleteMany(pattern), pruneExpired(), allKeys(), transaction(callable $fn, bool $write), close()Bulk delete, expiry sweep, the key list, a transaction, and close
Entrykey, value, binary, createdAt, modifiedAt, expiresAt; isExpired(), rawValue(); binary(key, bytes)A stored row. rawValue() decodes binary entries.
ImportCommandrun(format, path, atomic, ifExists, maxBytes)The import command as a method, returning an exit code
ExportCommandrun(format, ?dbName, ?pattern), exportToString(format, ?dbName, ?pattern)The export command, to stdout or to a string
JsonImporter, YamlImporterimportFromFile(path, atomic, ifExists, maxBytes), importFromString(text, ...)Import one document format, returning an ImportReport
FlatDocumentNormaliservalidatedOptions(), ttlMap(), binaryKeyList(), commit(store, rows, atomic, ifExists)Turns a flat document into validated rows and writes them under one import policy
YamlDialectbuild(array $flat), parse(string $yaml), reservedKeyReason(key)The YAML document shape: TTL and binary markers, and the keys the dialect reserves
ArgParserset(), get(), list(), delete(), import(), export(), prune()The CLI's argument parsing. Unknown options and surplus positionals are refused, not ignored.
ImportReportimported, overwritten, skippedThe counts an import returns
TtlinRange(int $seconds)The valid TTL range, 1 to 999999999 seconds

Only methods declared in candy-kv/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Kv

Database final class

SQLite-backed store for one named database.

MethodSummary
__construct(string $path, string $name, bool $create = true)
get(string $key): ?EntryGet a single entry by key. Returns null if not found or if the entry has expired.
raw(string $key): ?EntryGet a single entry by key, bypassing TTL / expiry filter. Returns null if not found.
set(string $key, string $value, bool $binary = false, ?int $ttlSeconds = null): EntrySet a value, creating or overwriting the entry.
delete(string $key): boolDelete an entry by key. Returns true if deleted, false if key was not present.
list(?string $pattern = null, bool $reverse = false, string $mode = 'all', string $delimiter = "\t"): \GeneratorList entries matching an optional glob pattern.
count(?string $pattern = null): intCount entries matching a pattern.
deleteMany(string $pattern): intDelete all LIVE entries matching a glob pattern. Returns the number of entries deleted.
pruneExpired(): intPhysically remove every already-expired entry.
allKeys(): arrayReturn all non-expired keys in this database.
static listDatabases(string $dataDir): arrayGet all database names from the config directory.
transaction(callable $fn, bool $write = true): mixedExecute a callback inside an atomic SQLite transaction.
close(): voidClose the database connection.

Entry final class

A single key/value entry in the store.

MethodSummary
__construct(string $key, string $value, bool $binary = false, ?\DateTimeImmutable $createdAt = null, ?\DateTimeImmutable $modifiedAt = null, ?\DateTimeImmutable $expiresAt = null)
isExpired(): boolWhether this entry has expired (applies only if expiresAt is set).
static fromRow(array $row): selfBuild from a database row (key, value, binary, created, modified[, expires_at]).
rawValue(): stringGet the raw (decoded) value if this is binary data.
static binary(string $key, string $bytes): selfCreate a binary entry from raw bytes.

Lang final class

Per-library translation facade for candy-kv.

Store final class

Main entry point for the candy-kv key/value store.

MethodSummary
__construct(?string $dataDir = null, string $defaultDb = 'default')Create a new Store handle.
set(string $key, string $value, bool $binary = false, ?int $ttlSeconds = null): EntrySet a value.
setWithTtl(string $key, mixed $value, int $ttlSeconds): voidSet a value that automatically expires after $ttlSeconds.
get(string $key, string $fallback = ''): stringGet a value by key.
suggestionFor(string $key): ?stringSuggest the closest existing key to $key, or null when nothing is near enough to help. Backs the CLI's "did you mean" line.
entry(string $key): ?EntryGet the full Entry object for a key (includes metadata).
static sanitizeForTty(string $value): stringRender a stored value safely for a one-line terminal (TTY) listing.
fuzzyFilter(string $query, ?string $dbName = null): arrayFilter entries using fuzzy search on keys.
suggestDatabase(string $dbName): ?stringThe nearest live database name to a typo'd one (kv-048), or null when nothing is close enough. Same codepoint law as the key hint — the two doors must not drift into different edit metrics.
delete(string $key): intDelete one or more keys.
list(?string $pattern = null, ?string $dbName = null, bool $reverse = false, string $mode = 'all', string $delimiter = "\t"): \GeneratorList entries in a database.
setFile(string $key, string $filePath): EntryStore binary data from a file path.
saveTo(string $key, string $filePath): boolWrite binary data from a key to a file path.
listDatabases(): arrayGet the list of all database names.
pruneExpired(): intRemove every already-expired entry from the default database and return how many rows were dropped.
pruneDatabase(string $dbName): intRemove every already-expired entry from one NAMED database (kv-025: pruneExpired() only saw the default db, so expired rows in the other files of the same store were unreachable — prune is a vault-wide hygiene job, not a default-database accident).
isReservedDatabase(string $dbName): boolTrue for the catalogued reserved names (S19). Public so a verb can order its doors honestly: a reserved database EXISTS even though listDatabases() hides it, and the write refusal is the informative answer — not 'does not exist'.
deleteDatabase(string $dbName): boolDelete an entire database (all its entries).
dataDir(): stringGet the data directory path.
defaultDatabase(): stringGet the default database name.
transaction(string $dbName, callable $fn): mixedExecute a callback inside an atomic transaction on a named database.
static splitKey(string $key, string $defaultDb): arrayThe key-spelling law as a pure function: split an import/export key into [database, entry key] using the same rightmost-unescaped-'@' rule Store::set() routes by. Importers derive their per-database transaction roster through HERE, so a key spelled a\@b (a literal at-sign) can never be misread as naming a second database — the naive strrpos() version of this walk used to route {"k@x":5,...} imports through a roster that silently missed x.
static hasRawGlob(string $key): boolkv-043: true when $key carries a * or ? byte that is NOT spelled with the pattern engine's escape. Same single-backslash lookback the '@' split applies — the grammar has no \\ self-escape (kv-007), so "escaped" always means "one backslash immediately before it".
static unescapeGlobKey(string $key): stringkv-043: the pattern engine's unescape as a pure key mapping — drop the backslash that spells a literal */? (\* → *, \? → ?). Every other backslash stays exactly as typed: the grammar has no self-escape, so \<x> for other x is literal text, mirroring Database::globToLike's "a backslash before anything else stays literal" law. This is what makes a get arg spelled ra\*wt name the key ra*wt instead of dying at the pattern gate.
static resolveDataDir(): stringResolve the data directory: $XDG_CONFIG_HOME/skate, then $HOME/.config/skate, then the passwd entry's home directory.

SugarCraft\Kv\Cli

ExportCommand final class

CLI command handler for candy-kv export.

MethodSummary
__construct(private readonly Store $store, private readonly mixed $stdout = \STDOUT, private readonly mixed $stderr = \STDERR)
run(string $format, ?string $dbName = null, ?string $pattern = null): intRun the export command.
exportToString(string $format, ?string $dbName = null, ?string $pattern = null): stringExport entries to a string (does not write to STDOUT).

ImportCommand final class

CLI command handler for candy-kv import.

MethodSummary
__construct(private readonly Store $store, private readonly mixed $stdout = \STDOUT, private readonly mixed $stderr = \STDERR)
run(string $format, string $path, bool $atomic = true, string $ifExists = 'replace', int $maxBytes = SizeCap::DEFAULT_MAX_BYTES): intRun the import command.

SugarCraft\Kv\Import

FlatDocumentNormaliser final class

The normalization law shared by both flat importers (candy-kv-063).

MethodSummary
static validatedOptions(array $options): arrayFail fast on the constructor ttl map (candy-kv-031): the options and a document share one write path, so they must share one law. A raw 'soon' used to leak a TypeError out of resolveTtl's return type where every document-level shape answers with a domain exception.
static ttlMap(mixed $map): arrayThe nested _ttl envelope, shared by the JSON top-level member and the YAML legacy symfony-route line: a map of key → whole seconds, or a refusal naming what arrived instead.
static binaryKeyList(mixed $list): arrayThe _binary name-list envelope: keys whose values are base64 of raw bytes. Without the flag a reimport would store the base64 text as the value, so the list must be exact.
static wholeSeconds(string $subject, mixed $seconds): intWhole seconds or a refusal — is_numeric admits floats and float-shaped strings; the store counts whole seconds, and (int) would silently truncate 1.5 to 1 while the text promises "integer". The subject is the sentence head ('_ttl entry "k"', 'TTL for entry "k"'), so each envelope spelling keeps its own voice on one law.
static resolveTtl(array $ttlMap, string $key): ?int
static validatedEntryKey(string $key, Store $store): voidThe key law pre-writes (candy-kv-030): Store::splitKey is the same authority Store::set routes by, and the walk happens BEFORE any row is committed — under atomic=false the old shape left prefix rows mutated and made the refuse-before-any-write law false for exactly this error class.
static refuseNonScalar(string $key, mixed $value): neverOne non-scalar refusal sentence for both formats (candy-kv-103 wording): the type name is not reliably consonant-led, so the article-free "of type %s" shape carries every get_debug_type value. Declared never because it always throws — the callers' rows-shape law depends on the analyzer knowing the branch cannot fall through.
static commit(Store $store, array $rows, bool $atomic, string $ifExists): ImportReportThe commit step (candy-kv-051 kernel + candy-kv-063 roster).

ImportCommit final class

The shared commit step behind both importers (candy-kv-051).

MethodSummary
static run(Store $store, array $rows, string $ifExists): ImportReport

ImportReport final class

Outcome of one committed import: what landed, what it replaced, what --if-exists=skip left alone.

MethodSummary
__construct(public readonly int $imported, public readonly int $overwritten, public readonly int $skipped)

JsonImporter final class

Imports key/value pairs into a Store from a JSON file.

MethodSummary
__construct(private readonly Store $store, array $options = [])
importFromFile(string $path, bool $atomic = true, string $ifExists = 'replace', int $maxBytes = SizeCap::DEFAULT_MAX_BYTES): ImportReportImport entries from a JSON file path.
importFromString(string $json, bool $atomic = true, string $ifExists = 'replace', int $maxBytes = SizeCap::DEFAULT_MAX_BYTES): ImportReportImport entries from a JSON string.

YamlImporter final class

Imports key/value pairs into a Store from a YAML file.

MethodSummary
__construct(private readonly Store $store, array $options = [])
importFromFile(string $path, bool $atomic = true, string $ifExists = 'replace', int $maxBytes = SizeCap::DEFAULT_MAX_BYTES): ImportReportImport entries from a YAML file path.
importFromString(string $yaml, bool $atomic = true, string $ifExists = 'replace', int $maxBytes = SizeCap::DEFAULT_MAX_BYTES): ImportReportImport entries from a YAML string.

SugarCraft\Kv\Support

InputPath final class

The shared allowlist law for every caller-supplied read path.

MethodSummary
static refuseStreamWrapper(string $path): stringRefuse a stream-wrapper URL, naming the scheme that was found.
static isStdinMarker(string $path): boolTrue for the two documented STDIN spellings the CLI accepts.

PluralChooser final class

Picks the CLDR cardinal plural form for a count message.

MethodSummary
static category(string $locale, int $n): stringCLDR category (zero|one|two|few|many|other) for a count.
static key(string $base, int $n, ?string $locale = null): stringCatalog key for $base at count $n, falling back toward _n when the locale does not carry the chosen suffix (a many that a Russian catalog folds into _n, an English few).
static t(string $base, int $n): stringTranslated counted line for $base at $n (always passes {count}).

SizeCap final class

The byte ceilings candy-kv-073 asked for: a multi-hundred-MB document used to buffer itself (and, on the symfony YAML route, several copies of itself) straight into an OOM kill that bypassed every "Import failed:" handler — the kernel, not the CLI, answered the oversized input.

MethodSummary
static refuseOversized(?int $bytes, int $maxBytes, string $source): voidRefuse a known size before touching the bytes.
static readStream($stream, int $maxBytes, string $source): ?stringRead a stream up to the ceiling, refusing the moment it grows past it — an unbounded STDIN never reaches the decoder, let alone the OOM killer. Returns null only on a plain read failure (the caller's door owns that domain message); an over-cap stream throws right here.

Ttl final class

The single documented TTL bound for every write channel.

MethodSummary
static inRange(int $seconds): boolTrue when $seconds is a storable positive TTL inside the horizon.

Version final class

The version string this tool reports on --version.

MethodSummary
static line(): stringThe --version line: plain text, newline-terminated, produced by no state and no host probe — the flag must answer anywhere.
static current(): stringThe version this process reports: the archive stamp when running from a stamped phar, self::CURRENT everywhere else.
static fromPharMetadata(string $path): ?stringThe version a phar archive at $path was built to carry, or null when it names none (unreadable archive, wrong metadata shape, the dev-build sentinel, or an empty stamp). Every refusal is a null, never an exception — --version must answer on a machine whose phar cannot be opened.
static versionFromMetadata(mixed $metadata): ?stringThe judgement on the stamp itself, split out because the archive-open leg is unreachable from a suite that must not build phars: the release namespace strip, the dev-build refusal, and the wrong-type nulls are a pure function over what getMetadata() answers.
static hostArchive(): stringThe filesystem path of the phar this process was launched from, or '' when it was not launched from one — the two-identity law measured on candy-code's real builds and pinned by the bin autoload guard: inside archive-loaded code Phar::running(false) answers the archive path, while the stub context answers '' and there a '.phar'-suffixed __DIR__ is the enclosing archive.

Configuration and data directory

candy-kv reads two environment variables, and neither one is required. The data directory is $XDG_CONFIG_HOME/skate when that is set, otherwise ~/.config/skate. The directory keeps the pre-rename skate name on disk, so installs from before the rename keep working.

SettingTypeDefaultEffect
XDG_CONFIG_HOMEabsolute pathunsetBase directory. The store lives in <base>/skate. A relative value is refused.
HOMEabsolute pathsystem valueUsed when XDG_CONFIG_HOME is unset. The store lives in <home>/.config/skate. A relative value is refused.

If neither variable is set, candy-kv falls back to the home directory in the passwd database. If even that is unavailable, it throws rather than writing into the install tree. Database names are limited to letters, digits, _ and -. The name settings is reserved: listDatabases() never shows it, and every write aimed at it is refused.

Upstream skate keeps its own data in a BadgerDB layout that this store cannot read. Move data across with export there and import here. JSON and YAML are the only bridge, and the two stores never share a directory.

Output discipline

get prints the exact stored bytes, with no newline added and nothing scrubbed, so $(candy-kv get k) round-trips honestly. get --sanitize collapses a value to one line, strips the C0 control bytes (ESC included) and DEL, and removes the C1 range, for terminal printing. Values reach the terminal through Store::sanitizeForTty().

Key naming, @db and escapes

A key is any string, with one syntax on top. A trailing @name routes the key to the database name, and a key without a suffix goes to the default database. \@ spells a literal at-sign in a key, and \* spells a literal star in a glob. Glob patterns support * and ?, and they are case-sensitive.

candy-kv set 'mail@work' hunter2          # stored in the work database, key "mail"
candy-kv set 'a\@b' 1                    # the key is the literal "a@b" in the default database
candy-kv list 'user-?'                   # one character after "user-"

Examples

The examples/ directory holds five runnable programs. Each one uses a temporary data directory, so none of them touches the real store:

  • examples/basic.php covers set(), get(), delete() and list(), the fallback value, and entry() for metadata.
  • examples/binary.php stores raw bytes with set(binary: true) and reads them back through rawValue().
  • examples/glob.php lists keys with * and ? glob patterns.
  • examples/multidb.php uses the key@dbname suffix to keep three named databases (passwords, bookmarks, notes) side by side, then deletes notes.
  • examples/reverse-order.php lists the same keys forward and in reverse order.
php examples/basic.php
php examples/multidb.php

Testing

The suite lives in tests/ and runs under PHPUnit 10. Run it from the package root, with stdin redirected so a stray read cannot hang the run:

vendor/bin/phpunit < /dev/null

The tests cover the store contract (StorageContractTest, StoreTest), the database and its TTL migration (DatabaseTest, DatabaseTtlMigrationTest), the import and export commands (ImportCommandTest, ImportExportTest), the YAML dialect (YamlDialectTest), and the CLI's argument contract (CliArgParserTest, CliContractTest).

Troubleshooting

set waits for input

candy-kv set key with no value reads standard input, silently, with no prompt. Pass the value on the command line, or pipe it in: printf 'value' | candy-kv set key.

An import refuses a top-level JSON array or YAML sequence

The document's top level is a JSON array or a YAML sequence. candy-kv refuses it with Expected a JSON object mapping keys to values, got a list. (JSON) or Expected a YAML mapping of keys to values, got a sequence. (YAML), rather than importing the indices as keys. Wrap the entries in an object that maps each key to its value.

An import refuses a null, boolean, array or object value

Those values cannot round-trip as stored text, so the whole import is refused before anything is written. Convert the value to a string in the source document.

A write to key@settings throws InvalidArgumentException

settings is reserved for a config database, which a list-driven backup must not mistake for a value database, so listDatabases() leaves it out. Write to a different database name. Reads of a planted key@settings still work.

A relative XDG_CONFIG_HOME or HOME is refused

A relative path would move the store with the working directory, so candy-kv refuses it. Set the variable to an absolute path. The refusal is an uncaught error, so the process exits 255 rather than 1.

A value with a NUL byte refuses under --text

Every reader truncates at the first NUL, so --text refuses the value with exit 2. Store it with --binary, or drop the --text flag and let the CLI choose binary mode.

Upstream mapping

Upstream (Go, charmbracelet/skate)candy-kv (PHP)
The skate command and its key/value verbsbin/candy-kv, ArgParser, and the commands behind them
Named databases through a key@db suffixStore::splitKey(), one SQLite file per database
BadgerDB storageSQLite through Database. Data does not move between the two without an export.

Architecture

Store routes, Database stores

Store owns the data directory and the routing. It resolves a key to its database and rejects reserved names. The rows and the SQL all sit in Database, so a transaction or a prune runs against one file at a time.

Import is a pipeline with one commit point

An importer parses its format (JsonImporter, YamlImporter), and FlatDocumentNormaliser validates every row before anything is written. ImportCommit then applies the replace, skip or fail policy. A value that cannot round-trip as stored text refuses the whole import before a single row is written.

Output is sanitized at the edge

A value bound for a terminal goes through Store::sanitizeForTty(), so a stored value that holds escape sequences cannot move the cursor or restyle the screen.

Changelog and versioning

candy-kv --version reports the version stamped into a phar build. A source checkout reports dev-master rather than an invented semver, so an unreleased tree never claims a release number.

  • sugar-core: the Util\Sanitize helper the store uses to clean values for the terminal, and the I18n\T wrapper behind the CLI's messages.

Try the quickstart →

Source & demos

Demos.

VHS-recorded GIFs of the shipped examples, plus one CLI session for the glob listing. Regenerated automatically on every push that touches the source.

Get / set / list

Get / set / list

File-backed store: set, get, list, delete.
Glob listing

Glob listing

List keys matching user-* and token-*. Recorded from the CLI (./bin/candy-kv), not from examples/glob.php.
Reverse-order list

Reverse-order list

List the same keys forward and in reverse key order.
Binary values

Binary values

Round-trip raw bytes in and out of the store.
Multiple DBs

Multiple DBs

Three named stores side by side, no collisions.