@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!
Maintainers
Readme
@nguyenetic/nexusql - TypeScript/Node.js Bindings
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, $2placeholders - ✅ 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/nexusqlyarn
yarn add @nguyenetic/nexusqlpnpm
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 databaseVector 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 indexTransaction Methods
const tx = await db.beginTransaction();
await tx.query(sql) // Query in transaction
await tx.commit() // Commit changes
await tx.rollback() // Rollback changesPrepared 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
- Always use parameterized queries for user input
- Use prepared statements for repeated queries
- Validate input before database operations
- Use transactions for multi-step operations
- 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/nexusqlBinary Compatibility
If you encounter binary compatibility issues:
npm rebuild @nguyenetic/nexusql --build-from-sourceWindows 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 -- --coverageSee examples/ for runnable test examples.
📚 Examples
Check out the examples/ directory for complete, runnable examples:
- basic-usage.js - Getting started with NexusQL
- parameterized-queries.js - SQL injection prevention
- transactions.js - ACID transaction patterns
- prepared-statements.js - Performance optimization
- vector-search.js - Semantic search and embeddings
🔄 Migration Guides
🤝 Contributing
See CONTRIBUTING.md for contribution guidelines.
📄 License
MIT License - See LICENSE for details.
🔗 Links
- GitHub: https://github.com/Nguyenetic/NexusQL
- npm: https://www.npmjs.com/package/@nguyenetic/nexusql
- Documentation: Full API Reference
- Issues: GitHub Issues
💡 Support
- 📖 Documentation: docs/
- 🐛 Bug Reports: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 🔒 Security: Security Policy
Built with ❤️ using Rust, N-API, and modern JavaScript
