npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@nguyenetic/nexusql

v3.4.0

Published

AI-Native, PostgreSQL-compatible database with vector search, HNSW indexing, and full ACID compliance. All 298 tests passing. NEW: PRAGMA statement support for SQLite compatibility!

Readme

@nguyenetic/nexusql - TypeScript/Node.js Bindings

npm version License: MIT Node.js Tests

AI-native, PostgreSQL-compatible database with vector search support. Fast, embedded, and easy to use with built-in SQL injection prevention.

🎉 Version 3.1.0 - Production Ready!

All 271 tests passing (100% success rate) - This release includes critical HNSW algorithm fixes and complete test suite validation. Production-ready with proper vector search implementation!

🚀 Features

  • Parameterized Queries - SQL injection prevention with $1, $2 placeholders
  • Prepared Statements - Compile once, execute many times (10× faster)
  • ACID Transactions - Full MVCC with automatic rollback
  • Vector Search - Built-in HNSW index for semantic search (1578× faster)
  • Async/Await - Modern promise-based API
  • TypeScript - Full type definitions included
  • Zero Config - Works out of the box

📦 Installation

npm

npm install @nguyenetic/nexusql

yarn

yarn add @nguyenetic/nexusql

pnpm

pnpm add @nguyenetic/nexusql

⚡ Quick Start

Basic Usage

import { NexusDb } from '@nguyenetic/nexusql';

const db = new NexusDb('./myapp.db');

// Create table
await db.execute(`
  CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE
  )
`);

// Insert with parameterized query (prevents SQL injection)
await db.execute(
  'INSERT INTO users VALUES ($1, $2, $3)',
  [1, 'Alice', '[email protected]']
);

// Query data
const result = await db.query('SELECT * FROM users WHERE id = $1', [1]);
console.log(result.rows[0]); // { id: 1, name: 'Alice', email: '[email protected]' }

await db.close();

Transactions

const tx = await db.beginTransaction();

try {
  await tx.query('INSERT INTO users VALUES (2, "Bob", "[email protected]")');
  await tx.query('UPDATE accounts SET balance = balance - 100 WHERE user_id = 2');
  await tx.commit(); // ✅ Both succeed
} catch (error) {
  await tx.rollback(); // ❌ Both fail
  console.error('Transaction failed:', error);
}

Prepared Statements (10× Faster)

const stmt = await db.prepare('INSERT INTO users VALUES ($1, $2, $3)');

// Execute multiple times with different parameters
for (let i = 1; i <= 1000; i++) {
  await stmt.execute(i, `User${i}`, `user${i}@example.com`);
}

await stmt.close();

Vector Search

// Create table with vector column
await db.execute(`
  CREATE TABLE documents (
    id INTEGER PRIMARY KEY,
    content TEXT,
    embedding VECTOR(384)
  )
`);

// Insert vector with metadata
const embedding = new Array(384).fill(0).map(() => Math.random());
await db.insertVector('documents', embedding, JSON.stringify({
  id: 1,
  content: 'Introduction to machine learning'
}));

// Batch insert (100× faster)
const vectors = Array.from({ length: 1000 }, () =>
  new Array(384).fill(0).map(() => Math.random())
);
const metadata = Array.from({ length: 1000 }, (_, i) => JSON.stringify({
  id: i + 1,
  content: `Document ${i + 1}`
}));
await db.batchInsertVectors('documents', vectors, metadata);

// Create HNSW index
await db.createVectorIndex('documents', 'embedding', 'hnsw', JSON.stringify({
  m: 16,
  ef_construction: 64,
  distance: 'cosine'
}));

// Semantic search
const queryVector = new Array(384).fill(0).map(() => Math.random());
const results = await db.query(`
  SELECT id, content, cosine_distance(embedding, $1) as similarity
  FROM documents
  ORDER BY similarity
  LIMIT 10
`, [JSON.stringify(queryVector)]);

📖 Complete API Reference

See the Full TypeScript API Documentation for detailed reference:

  • Classes - NexusDb, Transaction, PreparedStatement
  • Methods - Complete method reference with examples
  • Interfaces - QueryResult, Field
  • Examples - Real-world usage patterns

🔑 API Quick Reference

Database Operations

const db = new NexusDb(path: string);              // Create database instance

await db.query(sql, params?)                       // Execute SELECT query
await db.execute(sql, params?)                     // Execute INSERT/UPDATE/DELETE
await db.prepare(sql)                              // Create prepared statement
await db.beginTransaction()                        // Start transaction
await db.close()                                   // Close database

Vector Operations

await db.insertVector(table, vector, metadata?)              // Insert single vector
await db.batchInsertVectors(table, vectors, metadataArray?)  // Batch insert (10-100× faster)
await db.createVectorIndex(table, column?, type?, config?)   // Create HNSW index

Transaction Methods

const tx = await db.beginTransaction();

await tx.query(sql)                                // Query in transaction
await tx.commit()                                  // Commit changes
await tx.rollback()                                // Rollback changes

Prepared Statement Methods

const stmt = await db.prepare(sql);

await stmt.execute(...params)                      // Execute with parameters
await stmt.close()                                 // Close statement

🔒 Security

Parameterized Queries (SQL Injection Prevention)

// ✅ SAFE - Parameterized query
const userId = req.params.id;
const result = await db.query('SELECT * FROM users WHERE id = $1', [userId]);

// ❌ UNSAFE - String concatenation (NEVER do this!)
const result = await db.query(`SELECT * FROM users WHERE id = ${userId}`);

NexusQL automatically escapes all parameters to prevent SQL injection attacks.

Best Practices

  1. Always use parameterized queries for user input
  2. Use prepared statements for repeated queries
  3. Validate input before database operations
  4. Use transactions for multi-step operations
  5. Handle errors gracefully with try/catch

See Security Guide for comprehensive security practices.

💻 Platform Support

| Platform | Architecture | Status | |----------|-------------|--------| | Windows | x64 | ✅ Supported | | Windows | arm64 | ✅ Supported | | macOS | x64 (Intel) | ✅ Supported | | macOS | arm64 (Apple Silicon) | ✅ Supported | | Linux | x64 (glibc) | ✅ Supported | | Linux | x64 (musl) | ✅ Supported | | Linux | arm64 | ✅ Supported |

📊 Performance Tips

Use Prepared Statements for Bulk Operations

// ❌ SLOW - Individual executes (1000 queries = ~1000ms)
for (let i = 0; i < 1000; i++) {
  await db.execute('INSERT INTO users VALUES ($1, $2)', [i, `User${i}`]);
}

// ✅ FAST - Prepared statement (1000 executions = ~100ms)
const stmt = await db.prepare('INSERT INTO users VALUES ($1, $2)');
for (let i = 0; i < 1000; i++) {
  await stmt.execute(i, `User${i}`);
}
await stmt.close();

Use Batch Operations for Vectors

// ❌ SLOW - Individual inserts (1000 vectors = ~5000ms)
for (const vector of vectors) {
  await db.insertVector('embeddings', vector);
}

// ✅ FAST - Batch insert (1000 vectors = ~50ms)
await db.batchInsertVectors('embeddings', vectors);

Create Indexes for Better Query Performance

// Create index on frequently queried columns
await db.execute('CREATE INDEX idx_users_email ON users(email)');

// Create vector index for similarity search (1578× speedup)
await db.createVectorIndex('embeddings', 'embedding', 'hnsw');

🐛 Troubleshooting

Module Not Found

If you get "Cannot find module" errors:

npm install @nguyenetic/nexusql
# or
npm rebuild @nguyenetic/nexusql

Binary Compatibility

If you encounter binary compatibility issues:

npm rebuild @nguyenetic/nexusql --build-from-source

Windows File Locking

On Windows, always close databases properly:

try {
  const db = new NexusDb('./app.db');
  // ... use database
} finally {
  await db.close(); // Important on Windows!
}

In-Memory Databases for Testing

Use :memory: for tests to avoid file locking issues:

const db = new NexusDb(':memory:'); // No cleanup needed

📝 TypeScript Configuration

Add to your tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

🧪 Testing

npm test
npm test -- --coverage

See examples/ for runnable test examples.

📚 Examples

Check out the examples/ directory for complete, runnable examples:

🔄 Migration Guides

🤝 Contributing

See CONTRIBUTING.md for contribution guidelines.

📄 License

MIT License - See LICENSE for details.

🔗 Links

💡 Support


Built with ❤️ using Rust, N-API, and modern JavaScript