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

@awenk/sqlite-model-builder

v1.5.3

Published

Dynamic Query Builder & Mini ORM for Node.js + SQLite

Readme

SQLite Model Builder

Dynamic Query Builder & Mini ORM for Node.js + SQLite


🚀 Overview

SQLite Model Builder adalah query builder ringan dan fleksibel untuk SQLite di Node.js.
Terinspirasi dari Eloquent (Laravel) dan Knex, tapi lebih sederhana — cukup satu file, tanpa ORM berat.
Mendukung query dinamis, chaining, filter, agregasi, dan auto-create database jika belum ada.


🧰 Fitur Utama

  • ⚙️ Auto-create SQLite DB jika belum ada
  • 🔗 Chained query builder mirip Eloquent
  • 🧮 Fungsi agregat (count, sum, avg)
  • 🔍 Filter fleksibel (where, whereIn, whereLikeAny)
  • 🔀 join, orderBy, groupBy, having
  • 📄 paginate() dan first()
  • 🧾 Support transaksi (beginTransaction, commit, rollback)
  • 💾 CRUD sederhana (insert, update, delete)
  • 🧠 Tanpa ORM berat — hanya helper modular untuk SQLite

⚡ Fitur Query Builder

| Fungsi | Deskripsi | | ---------------------------------------------- | ----------------------- | | .select(fields) | Pilih kolom | | .where(field, value) | Filter | | .whereIn(field, [values]) | Filter array | | .whereLikeAny(field, keyword) | Pencarian LIKE otomatis | | .join(table, localKey, operator, foreignKey) | Join tabel | | .orderBy(field, direction) | Urutkan | | .groupBy(field) | Grouping | | .having(condition) | Kondisi group | | .limit(n) | Batas hasil | | .paginate(page, perPage) | Pagination otomatis | | .count(field) | Hitung jumlah | | .sum(field) / .avg(field) | Agregat | | .first() | Ambil 1 record | | .get() | Ambil semua | | .insert(data) | Tambah data | | .update(data) | Ubah data | | .delete() | Hapus data |


🧩 Transaksi

const trx = await User.beginTransaction();

try {
  await trx.insert({ name: 'Bob', email: '[email protected]' });
  await trx.commit();
} catch (err) {
  await trx.rollback();
  console.error('Transaction failed:', err);
}

📘 Contoh Penggunaan

// test.js
const { initDB, Model } = require('@awenk/sqlite-model-builder');

let db = null;

// 🔹 Helper untuk inisialisasi koneksi SQLite sekali saja
async function getDB() {
  if (!db) {
    // 1️⃣ Mode default (baca/tulis file, auto-create folder)
    db = await initDB({ filename: './data/app.sqlite', verbose: true });

    // 2️⃣ Mode readonly
    // db = await initDB({ filename: './data/app.sqlite', readonly: true });

    // 3️⃣ Mode in-memory
    // db = await initDB({ memory: true, verbose: true });
  }
  return db;
}

(async () => {
  await getDB(); // Init connection sekali saja

  // Buat tabel contoh (kalau belum ada)
  await db.exec(`
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT,
      email TEXT,
      age INTEGER DEFAULT 18,
      role TEXT DEFAULT 'user',
      status TEXT DEFAULT 'active',
      created_at TEXT DEFAULT CURRENT_TIMESTAMP
    );

    CREATE TABLE posts (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      user_id INTEGER,
      title TEXT
    );
  `);

  // 🧩 Insert data
  await Model('users').insert({ name: 'Andi', email: '[email protected]' });
  await Model('posts').insert({ user_id: 1, title: 'TEST POSTS' });

  // 🧩 Update data
  await Model('users').where('id',1).update({ name: 'Update Name' });

  // 🧩 Delete data
  await Model('users').where('id',2).delete();

  // 🧩 Ambil semua user
  const users = await Model('users').orderBy('id', 'DESC').get();
  console.log('Users:', users);

  // 🧩 Filter + Like
  const active = await Model('users')
    .where('status','active') //singe condition | .where({status: 'active', role: 'admin' })   // multiple condition otomatis    
    .whereOp('age','<', 20)
    .whereLike('name', 'andi')
    .get();
  console.log('Filtered:', active);

  // 🧩 Aggregate
  const total = await Model('users').count();
  console.log('Total users:', total);

  const sum = await Model('orders').sum('amount');
  console.log('Sum amount:', sum);

  // 🧩 Pagination
  const paged = await Model('users').paginate(2, 10);
  console.log('Paged:', paged);

  // 🧩 Exist
  const usersExist = await Model('users').where('status', 'active').exists();
  console.log('Ada user aktif?', usersExist); // true/false

  // 🧩 Select Satu Kolom
  const emails = await Model('users').where('status', 'active').pluck('email');
  console.log(emails); // ['[email protected]', '[email protected]', ...]

  // 🧩 JOIN
  const resultJoin = await Model('posts')
    .select(['posts.id', 'posts.title', 'users.name AS author'])
    .join('users', 'posts.user_id', '=', 'users.id')
    .get();
  console.log(resultJoin);

 // 🧩 LEFT JOIN
  const resultLeftJoin = await Model('posts')
    .select(['posts.id', 'posts.title', 'users.name AS author'])
    .leftJoin('users', 'posts.user_id', '=', 'users.id')
    .get();
 console.log(resultLeftJoin);

  // 🧩 Min Max
  const minAge = await Model('users').where('status', 'active').min('age');
  const maxAge = await Model('users').where('status', 'active').max('age');
  console.log({ minAge, maxAge });
})();
/*multiple Database*/
const { initDB, ModelClass } = require('@awenk/sqlite-model-builder');

(async () => {
  const dbA = await initDB({ filename: './data/a.sqlite' });
  const dbB = await initDB({ filename: './data/b.sqlite' });

  // Pakai koneksi A
  const modelA = new ModelClass(dbA, 'users');
  const usersA = await modelA.select('*').get();
  console.log(usersA);

  // Pakai koneksi B
  const modelB = new ModelClass(dbB, 'users');
  const usersB = await modelB.select('*').get();
  console.log(usersB);
})();

📦 Instalasi

npm install github:badueny/sqlite-model-builder sqlite sqlite3

OR

npm install @awenk/sqlite-model-builder sqlite sqlite3

🧠 Lisensi

MIT © 2025 bitdev.id Author: Awenk

Node.js CI npm version license Node.js Version