# Cara Mengakses Database better-sqlite3

## 📍 Lokasi Database
- **Path relatif**: `data/users.db`
- **Path lengkap**: `E:\PROJECT\ddddd\Web-Antrean - Copy (2)\data\users.db`

---

## 🔧 Metode 1: Menggunakan Node.js Script (Recommended)

Karena project ini sudah menggunakan `better-sqlite3`, cara termudah adalah membuat script Node.js:

### Contoh Script untuk Query Database

```javascript
// scripts/query-db.js
const Database = require('better-sqlite3');
const path = require('path');

const dbPath = path.join(__dirname, '..', 'data', 'users.db');
const db = new Database(dbPath);

// Contoh: Get all users
const users = db.prepare('SELECT * FROM users').all();
console.log('All users:', users);

// Contoh: Get user by ID
const user = db.prepare('SELECT * FROM users WHERE id = ?').get('user-id-here');
console.log('User:', user);

// Contoh: Count users
const count = db.prepare('SELECT COUNT(*) as total FROM users').get();
console.log('Total users:', count.total);

db.close();
```

**Jalankan dengan:**
```bash
node scripts/query-db.js
```

---

## 🔧 Metode 2: Menggunakan SQLite CLI

### Install SQLite CLI (jika belum ada)

**Windows:**
1. Download dari: https://www.sqlite.org/download.html
2. Atau install via Chocolatey: `choco install sqlite`
3. Atau install via Scoop: `scoop install sqlite`

**Atau gunakan npx (tidak perlu install):**
```bash
npx sqlite3 data/users.db
```

### Perintah SQLite CLI

```bash
# Buka database
sqlite3 data/users.db

# Atau dengan npx (jika SQLite tidak terinstall)
npx sqlite3 data/users.db

# Di dalam SQLite shell:
.tables                    # Lihat semua tabel
.schema users              # Lihat schema tabel users
SELECT * FROM users;        # Lihat semua data
SELECT * FROM users LIMIT 10;  # Lihat 10 baris pertama
.mode column               # Format output sebagai kolom
.headers on                # Tampilkan header kolom
.quit                      # Keluar
```

---

## 🔧 Metode 3: Menggunakan GUI Tools

### 1. **DB Browser for SQLite** (Gratis, Recommended)
- Download: https://sqlitebrowser.org/
- Buka file: `data/users.db`
- Bisa edit, query, dan export data dengan mudah

### 2. **SQLiteStudio** (Gratis)
- Download: https://sqlitestudio.pl/
- Cross-platform, open source

### 3. **DBeaver** (Gratis)
- Download: https://dbeaver.io/
- Universal database tool, support banyak database termasuk SQLite

### 4. **VS Code Extension**
- Install extension: **SQLite Viewer** atau **SQLite**
- Buka file `data/users.db` langsung di VS Code

---

## 🔧 Metode 4: Menggunakan API Endpoints yang Sudah Ada

Project ini sudah punya API endpoints untuk mengakses data:

```bash
# Get all users
GET /api/users/list

# Get current user
GET /api/users/current

# Get user by ID
GET /api/users/[id]

# Create user
POST /api/users/create

# Update user
PATCH /api/users/[id]

# Delete user
DELETE /api/users/[id]
```

---

## 📊 Contoh Query Berguna

### Melihat semua users:
```sql
SELECT * FROM users;
```

### Melihat users dengan format tanggal yang readable:
```sql
SELECT 
  id,
  namaLengkap,
  namaUser,
  email,
  datetime(lastLogin, 'unixepoch') as lastLoginFormatted,
  datetime(createdAt, 'unixepoch') as createdAtFormatted
FROM users;
```

### Mencari user berdasarkan nama:
```sql
SELECT * FROM users WHERE namaLengkap LIKE '%nama%';
```

### Mencari user berdasarkan username:
```sql
SELECT * FROM users WHERE namaUser = 'username';
```

### Melihat users yang belum login:
```sql
SELECT * FROM users WHERE lastLogin IS NULL;
```

### Melihat users yang baru dibuat:
```sql
SELECT * FROM users ORDER BY createdAt DESC LIMIT 10;
```

### Export data ke CSV:
```sql
.mode csv
.headers on
.output users_export.csv
SELECT * FROM users;
.output stdout
```

---

## ⚠️ Catatan Penting

1. **Backup sebelum edit manual**: Selalu backup database sebelum melakukan perubahan manual
2. **Tutup koneksi**: Pastikan aplikasi tidak sedang menggunakan database saat mengedit manual
3. **Format timestamps**: `lastLogin`, `createdAt`, `updatedAt` disimpan sebagai Unix timestamp (seconds)
4. **JSON fields**: `roles`, `realmRoles`, `accountRoles`, `resourceRoles`, `groups` disimpan sebagai JSON string

---

## 🛠️ Quick Access Script

Buat file `scripts/db-access.js` untuk akses cepat:

```javascript
const Database = require('better-sqlite3');
const path = require('path');
const readline = require('readline');

const dbPath = path.join(process.cwd(), 'data', 'users.db');
const db = new Database(dbPath);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log('📊 Database Access Tool');
console.log('Database path:', dbPath);
console.log('\nAvailable commands:');
console.log('  list - List all users');
console.log('  count - Count total users');
console.log('  schema - Show table schema');
console.log('  query <SQL> - Run custom SQL query');
console.log('  exit - Exit\n');

function prompt() {
  rl.question('> ', (input) => {
    const [cmd, ...args] = input.trim().split(' ');
    
    try {
      switch(cmd.toLowerCase()) {
        case 'list':
          const users = db.prepare('SELECT id, namaLengkap, namaUser, email FROM users').all();
          console.table(users);
          break;
        case 'count':
          const count = db.prepare('SELECT COUNT(*) as total FROM users').get();
          console.log(`Total users: ${count.total}`);
          break;
        case 'schema':
          const schema = db.prepare("PRAGMA table_info(users)").all();
          console.table(schema);
          break;
        case 'query':
          const sql = args.join(' ');
          if (!sql) {
            console.log('Error: Please provide SQL query');
            break;
          }
          const result = db.prepare(sql).all();
          console.table(result);
          break;
        case 'exit':
          db.close();
          rl.close();
          return;
        default:
          console.log('Unknown command. Type "exit" to quit.');
      }
    } catch (error) {
      console.error('Error:', error.message);
    }
    
    prompt();
  });
}

prompt();
```

Jalankan dengan: `node scripts/db-access.js`



