Skip to content

Nagibaba/NQL

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

NQL: Natural Query Language

A standardized query language enabling AI agents to safely access databases through natural language with human oversight.

Overview

NQL provides a three-layer architecture for translating natural language queries into database operations with built-in safety guarantees.

Natural Language → NQL (structured) → HQL (approval) → SQL/GraphQL/MongoDB

Key Features

  • Schema-aware AI: Eliminates field hallucination through context injection
  • Human approval gate: Template-based explanations ensure safety
  • Pluggable authentication: Works with any auth system
  • Auto-introspection: Generate schema from existing databases
  • Universal backend: PostgreSQL, MySQL, MongoDB, GraphQL, REST APIs
  • Framework agnostic: Works with React, Vue, Angular, vanilla JS

Quick Start

Installation

npm install -g @nql/cli
npm install @nql/core

Generate Schema

# Auto-generate from your database
nql introspect \
  --database postgres://localhost/mydb \
  --output schema.yaml

Basic Usage

const { NQLClient } = require('@nql/core');

const client = new NQLClient({
  schema: './schema.yaml',
  database: {
    type: 'postgresql',
    connection: process.env.DATABASE_URL
  },
  authAdapter: new YourAuthAdapter()
});

// Execute natural language query
const result = await client.execute(
  "Show me active users from last month",
  { request }  // Contains auth token
);

console.log(result.data);

Architecture

┌──────────────────────────────────────────────────┐
│  User: "Show me my pending orders"              │
└────────────────────┬─────────────────────────────┘
                     │
                     ↓
┌──────────────────────────────────────────────────┐
│  Schema Context Injection                        │
│  ┌────────────────────────────────────────────┐  │
│  │ resources:                                 │  │
│  │   orders:                                  │  │
│  │     fields:                                │  │
│  │       status: enum [pending|completed]     │  │
│  └────────────────────────────────────────────┘  │
└────────────────────┬─────────────────────────────┘
                     │
                     ↓
┌──────────────────────────────────────────────────┐
│  AI Query Generation                             │
│  {                                               │
│    "operation": "read",                          │
│    "resource": "orders",                         │
│    "params": {                                   │
│      "filter": {                                 │
│        "status": { "$eq": "pending" }            │
│      }                                           │
│    }                                             │
│  }                                               │
└────────────────────┬─────────────────────────────┘
                     │
                     ↓
┌──────────────────────────────────────────────────┐
│  Authentication & Authorization                  │
│  Your auth adapter checks permission             │
└────────────────────┬─────────────────────────────┘
                     │
                     ↓
┌──────────────────────────────────────────────────┐
│  Row-Level Security Injection                    │
│  Filter: customer_id = current_user              │
└────────────────────┬─────────────────────────────┘
                     │
                     ↓
┌──────────────────────────────────────────────────┐
│  HQL Generation (Template-Based)                 │
│  You're about to READ order records              │
│  Conditions:                                     │
│    - status equals "pending"                     │
│    - customer_id equals your ID (auto)           │
│  Risk: SAFE                                      │
│  Scope: MULTIPLE RECORDS                         │
└────────────────────┬─────────────────────────────┘
                     │
                     ↓
┌──────────────────────────────────────────────────┐
│  User Approval                                   │
│  [Preview] [Cancel] [Approve]                    │
└────────────────────┬─────────────────────────────┘
                     │ (if approved)
                     ↓
┌──────────────────────────────────────────────────┐
│  SQL Translation & Execution                     │
│  SELECT * FROM orders                            │
│  WHERE status = 'pending'                        │
│    AND customer_id = 'uuid-123'                  │
└────────────────────┬─────────────────────────────┘
                     │
                     ↓
┌──────────────────────────────────────────────────┐
│  Results with Metadata                           │
│  { data: [...], metadata: {...} }                │
└──────────────────────────────────────────────────┘

Example

User asks: "Delete banned users"

NQL Generated:

{
  "operation": "delete",
  "resource": "users",
  "params": {
    "filter": {
      "status": { "$eq": "banned" }
    }
  }
}

HQL Approval Dialog:

WARNING: DELETION OPERATION

You're about to DELETE user records PERMANENTLY

Conditions:
  - status equals "banned"

Risk: HIGH
Scope: MULTIPLE RECORDS

THIS CANNOT BE UNDONE

[Preview affected records] [Cancel] [Continue]

SQL Executed (if approved):

DELETE FROM users WHERE status = 'banned'

Core Concepts

1. Schema-Aware AI

Database schema is injected into AI prompts to prevent hallucination:

# schema.yaml
resources:
  users:
    fields:
      email:
        type: email
        sensitive: true
      status:
        type: enum
        values: ["active", "inactive", "banned"]

AI sees available fields and generates valid queries using real column names.

2. Template-Based Approval

Human explanations use deterministic templates (not AI) for safety:

Template: You're about to {OPERATION} {RESOURCE} records
Risk: {RISK_LEVEL}
Scope: {SCOPE}

No AI hallucination in safety-critical explanations.

3. Pluggable Authentication

Bring your own auth system:

class YourAuthAdapter {
  async extractContext(request) {
    // Use YOUR auth system
    const session = await yourAuth.getSession(request);
    return { user_id: session.userId, role: session.role };
  }
  
  async checkPermission(userContext, operation, resource) {
    // Use YOUR permission logic
    return await yourPerms.check(userContext, operation, resource);
  }
  
  async applyRLS(nqlQuery, userContext) {
    // Use YOUR row-level security rules
    return yourRLS.apply(nqlQuery, userContext);
  }
}

4. Auto-Introspection

Generate schema automatically:

nql introspect --database $DATABASE_URL --output schema.yaml

Detects:

  • Tables and columns
  • Data types
  • Foreign keys
  • Enums
  • Sensitive fields (email, password, etc.)
  • Unique constraints

Documentation

Getting Started

  • NQL Guide - Learn NQL with examples (start here!)

Core Concepts

  • NQL Language - Developer-friendly guide to writing NQL queries
  • HQL - Human approval layer explained
  • Specification - Formal language specification

Guides

Community

Comparison

Feature NQL GraphQL OData Direct SQL
Natural language input Yes No No No
AI-friendly syntax Yes Moderate No Moderate
Human approval gate Yes No No No
Schema awareness Built-in Required Optional Manual
Auth integration Pluggable App-level App-level Manual
Backend support Universal GraphQL only REST/OData Database-specific
Auto-introspection Yes No No No

Status

Version: 1.0.0-draft
Status: Specification phase
Reference implementation: Q1 2025

This is a specification under active development. The API may change before 1.0 release.

Contributing

Contributions welcome! See CONTRIBUTING.md for guidelines.

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Submit a pull request

License

MIT License - see LICENSE file

Citation

If you use NQL in academic work:

@misc{nql2024,
  title={NQL: Natural Query Language for AI Database Access},
  author={nagibaba},
  year={2024},
  url={https://github.com/nagibaba/nql}
}

Contact

  • GitHub Issues: Bug reports and feature requests
  • Discussions: Technical questions and proposals
  • Author: @nagibaba

About

Natural Query Language. AI as user interface

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published