JSON File Driver for Database-JS

raw JSON →
1.2.1 verified Thu Apr 23 auth: no javascript

database-js-json is a driver for the database-js2 ecosystem, enabling SQL-like querying of local JSON files. It wraps the jl-sql-api library to provide its core parsing and querying capabilities. The current stable version is 1.2.1, with releases adhering to Semantic Versioning. This package distinguishes itself by allowing developers to treat JSON documents as a data source queryable via a familiar SQL syntax, integrating seamlessly with the database-js2 connection abstraction. Key features include configurable character sets and file existence checks through URL-style connection string options. It's designed for scenarios requiring direct interaction with JSON data files using a standardized database interface, primarily for read operations.

error Error: ENOENT: no such file or directory, open 'test.json'
cause The specified JSON file path is incorrect or the file does not exist, and the `checkOnConnect` option is implicitly or explicitly set to `true`.
fix
Verify the JSON file exists at the specified path relative to your application's execution context, or append ?checkOnConnect=false to the connection string to bypass the check.
error Error: Protocol 'json' not found
cause The `database-js-json` driver has not been properly loaded or required, thus `database-js2` is unaware of how to handle the `json://` connection protocol.
fix
Ensure database-js-json is installed (npm install database-js-json) and explicitly required or imported in your application's entry point: require('database-js-json');.
error Error: SQL parse error: Unexpected token: <token>
cause The SQL-like query provided is syntactically incorrect or uses features not supported by the underlying `jl-sql-api` parser.
fix
Review the query syntax against the jl-sql-api documentation for supported grammar and operations. Ensure proper quotation for string literals and valid identifiers.
breaking This driver is specifically designed for `database-js2`, a modern fork of `database-js`. Attempting to use it with the original `database-js` package will result in errors due to incompatible APIs and protocol registration mechanisms.
fix Ensure `database-js2` is installed via `npm install database-js2` and that `Connection` is imported from `'database-js2'`, not `'database-js'`.
gotcha Configuration options (e.g., `charset`, `checkOnConnect`) are passed directly in the connection string as URL query parameters. For nested options originating from `jl-sql-api`, dot notation is required (e.g., `sortOptions.inMemoryBufferSize`).
fix Format connection strings correctly, for example: `json:///file.json?charset=utf-16&sortOptions.inMemoryBufferSize=32000`.
gotcha By default (`checkOnConnect=true`), the driver will throw an error if the specified JSON file does not exist upon connection. This can be problematic if the file is expected to be created later or if its initial absence should be ignored.
fix To suppress the file existence check, append `?checkOnConnect=false` to your connection string: `json:///test.json?checkOnConnect=false`.
npm install database-js-json
yarn add database-js-json
pnpm add database-js-json

Demonstrates connecting to a JSON file, querying data with a prepared statement, and closing the connection, including setup for a dummy JSON file.

const { Connection } = require('database-js2');
require('database-js-json'); // Ensure the driver is loaded and registers itself

(async () => {
    // Create a dummy JSON file for demonstration
    require('fs').writeFileSync('test.json', JSON.stringify([
        { "id": 1, "user_name": "alpha_user", "email": "alpha@example.com" },
        { "id": 2, "user_name": "beta_user", "email": "beta@example.com" },
        { "id": 3, "user_name": "not_so_secret_user", "email": "secret@example.com" }
    ], null, 2));

    const connection = new Connection( 'json:///test.json' );
    
    try {
        console.log('Connecting to json:///test.json...');
        // Query with a prepared statement
        let statement = await connection.prepareStatement("SELECT * WHERE user_name = ?");
        let rows = await statement.query('not_so_secret_user');
        console.log('Query result for "not_so_secret_user":', rows);
        console.log(`Found ${rows.length} user(s) matching the criteria.`);

        // Fetch all data
        let allRows = await connection.query("SELECT id, user_name FROM * LIMIT 2");
        console.log('First 2 entries:', allRows);

    } catch (error) {
        console.error('An error occurred:', error);
    } finally {
        await connection.close();
        console.log('Connection closed.');
        // Clean up the dummy file
        require('fs').unlinkSync('test.json');
    }
} )();