diff --git a/doc/api/sqlite.md b/doc/api/sqlite.md index 422df94ea540..f2e51028bf6f 100644 --- a/doc/api/sqlite.md +++ b/doc/api/sqlite.md @@ -921,6 +921,68 @@ console.log(allUsers); // ] ``` +### `database.createCollation(name, compare)` + + + +* `name` {string} The name of the collation. Like other SQLite names, it is not + case-sensitive. +* `compare` {Function} The function to call to compare two strings. It + receives the two strings and returns a negative number if the first string + sorts before the second, a positive number if it sorts after, and zero if + they are equal. The result is converted to a number, as with the compare + function of [`Array.prototype.sort()`][], and `NaN` means equal. + +Creates a collation, or replaces an existing one with the same name. SQL can +then use it in `COLLATE` clauses and in table and index definitions. This +method is a wrapper around [`sqlite3_create_collation_v2()`][]. + +`compare` must always return the same result for the same two strings, as +SQLite relies on that to keep indexes consistent. + +SQLite has no way for a collation to report an error. If `compare` throws, the +statement that called it is stopped with [`sqlite3_interrupt()`][], and the +exception is thrown from the method that ran the statement. As with any +interrupted statement, if it was changing the database, its changes are rolled +back, along with the open transaction if there is one. Interrupting also stops +any other statement that is running on the same connection at the time. + +```cjs +const { Database } = require('node:sqlite'); + +const db = new Database(':memory:'); + +db.createCollation('locale', (a, b) => a.localeCompare(b)); +db.exec(` + CREATE TABLE artists (name TEXT); + INSERT INTO artists VALUES ('Zebra'), ('Ágætis'), ('apple'); +`); + +console.log( + db.prepare('SELECT name FROM artists ORDER BY name COLLATE locale').all(), +); +// Prints: [ { name: 'Ágætis' }, { name: 'apple' }, { name: 'Zebra' } ] +``` + +```mjs +import { Database } from 'node:sqlite'; + +const db = new Database(':memory:'); + +db.createCollation('locale', (a, b) => a.localeCompare(b)); +db.exec(` + CREATE TABLE artists (name TEXT); + INSERT INTO artists VALUES ('Zebra'), ('Ágætis'), ('apple'); +`); + +console.log( + db.prepare('SELECT name FROM artists ORDER BY name COLLATE locale').all(), +); +// Prints: [ { name: 'Ágætis' }, { name: 'apple' }, { name: 'Zebra' } ] +``` + ### `database.createModule(name, options)`