// duckdb_crud.js
const duckdb = require('@duckdb/duckdb-node');
const fs = require('fs');
const path = require('path');
// Define a path for the database file
const dbPath = path.join(__dirname, 'my_duckdb_database.duckdb');
async function runDuckDBCrud() {
let db;
let connection;
try {
// Open the database
// Use :memory: for in-memory, or a file path for persistent storage
db = new duckdb.Database(dbPath);
connection = await db.connect(); // Get a connection to execute queries
console.log('DuckDB: Database opened and connection established successfully.');
// 1. CREATE Table
await connection.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY, -- DuckDB doesn't have AUTOINCREMENT, often use UUIDs or manage IDs manually for true uniqueness
name VARCHAR NOT NULL,
age INTEGER
)
`);
console.log('DuckDB: Table "users" ensured (created if not exists).');
// Note on `id INTEGER PRIMARY KEY`: DuckDB's `INTEGER PRIMARY KEY` is similar to `ROWID` in SQLite, meaning it's an alias for the internal row ID.
// It's unique and automatically assigned for inserts without specifying `id`. For true, portable, auto-incrementing IDs,
// you might use `BIGINT` and manage incrementing yourself or use UUIDs.
// For simplicity, we'll let DuckDB manage it implicitly for `INSERT` where ID is omitted.
// 2. INSERT Data
// For the first insert, omit ID to let DuckDB assign its internal rowid-like ID
await connection.run(
'INSERT INTO users (name, age) VALUES (?, ?)',
['Alice', 30]
);
console.log('DuckDB: Inserted Alice.');
// For subsequent inserts, DuckDB will continue to use the next available internal ID if `id` is omitted.
await connection.run(
'INSERT INTO users (name, age) VALUES (?, ?), (?, ?)',
['Bob', 25, 'Charlie', 35]
);
console.log('DuckDB: Inserted Bob and Charlie.');
// You can also insert explicitly with an ID if it's unique:
// await connection.run('INSERT INTO users (id, name, age) VALUES (10, ?, ?)', ['David', 40]);
// console.log('DuckDB: Inserted David with explicit ID 10.');
// 3. READ Data
console.log('\nDuckDB: All users:');
const allUsers = await connection.all('SELECT * FROM users ORDER BY id'); // DuckDB has no 'get', use 'all'
allUsers.forEach(user => {
console.log(`- ID: ${user.id}, Name: ${user.name}, Age: ${user.age}`);
});
console.log('\nDuckDB: User named Bob:');
const bob = await connection.all('SELECT * FROM users WHERE name = ?', ['Bob']);
if (bob.length > 0) {
console.log(`- ID: ${bob[0].id}, Name: ${bob[0].name}, Age: ${bob[0].age}`);
}
// 4. UPDATE Data
const updateResult = await connection.run(
'UPDATE users SET age = ? WHERE name = ?',
[31, 'Alice']
);
console.log(`DuckDB: Updated Alice's age (Rows affected: ${updateResult.changes})`);
console.log('\nDuckDB: Alice after update:');
const updatedAlice = await connection.all('SELECT * FROM users WHERE name = ?', ['Alice']);
if (updatedAlice.length > 0) {
console.log(`- ID: ${updatedAlice[0].id}, Name: ${updatedAlice[0].name}, Age: ${updatedAlice[0].age}`);
}
// 5. DELETE Data
const deleteResult = await connection.run('DELETE FROM users WHERE name = ?', ['Charlie']);
console.log(`DuckDB: Deleted Charlie (Rows affected: ${deleteResult.changes})`);
console.log('\nDuckDB: All users after deletion:');
const usersAfterDelete = await connection.all('SELECT * FROM users ORDER BY id');
usersAfterDelete.forEach(user => {
console.log(`- ID: ${user.id}, Name: ${user.name}, Age: ${user.age}`);
});
} catch (error) {
console.error('DuckDB Error:', error.message);
} finally {
if (connection) {
await connection.close();
console.log('DuckDB: Connection closed.');
}
if (db) {
await db.close();
console.log('DuckDB: Database closed.');
}
// Clean up the database file for consistent runs if desired
// try {
// if (fs.existsSync(dbPath)) {
// fs.unlinkSync(dbPath);
// console.log(`DuckDB: Removed database file: ${dbPath}`);
// }
// } catch (err) {
// console.error('Error cleaning up DuckDB file:', err);
// }
}
}
runDuckDBCrud();