QueryLeaf:用于 Mongo 的 SQL 查询引擎

Navigation Menu(导航菜单,此处省略,原文中均为站内链接)

beekeeper-studio / queryleaf Public

SQL for Mongo (使用 Node JS) queryleaf.com

License

View license 19 stars 0 forks Branches Tags Activity Star Notifications You must be signed in to change notification settings

Additional navigation options

beekeeper-studio/queryleaf

main BranchesTags Go to file Code

Folders and files

Name| Name| Last commit message| Last commit date ---|---|---|---

Latest commit

History

88 Commits .github/workflows| .github/workflows bin| bin docs| docs packages| packages .eslintrc.js| .eslintrc.js .gitignore| .gitignore .prettierrc| .prettierrc CLAUDE.md| CLAUDE.md COMMERCIAL_LICENSE.md| COMMERCIAL_LICENSE.md CONTRIBUTING.md| CONTRIBUTING.md LICENSE.md| LICENSE.md README-monorepo.md| README-monorepo.md README.md| README.md SECURITY.md| SECURITY.md TODO.md| TODO.md code_of_conduct.md| code_of_conduct.md jest.config.js| jest.config.js logo-green-bg-white-shape.png| logo-green-bg-white-shape.png logo-green.svg| logo-green.svg logo-transparent-bg-black-shape.png| logo-transparent-bg-black-shape.png logo-transparent-bg-green-shape.png| logo-transparent-bg-green-shape.png logo-transparent-bg-white-shape.png| logo-transparent-bg-white-shape.png logo-white.svg| logo-white.svg logo.svg| logo.svg mkdocs.yml| mkdocs.yml package.json| package.json requirements.txt| requirements.txt tsconfig.base.json| tsconfig.base.json tsconfig.json| tsconfig.json yarn.lock| yarn.lock View all files

Repository files navigation

QueryLeaf Logo

QueryLeaf

用于 NodeJS 的 SQL 到 MongoDB 查询转换器

Overview (概述)

QueryLeaf 是一个将 SQL 查询转换为 MongoDB 命令的库。 它使用 node-sql-parser 解析 SQL,将其转换为抽象命令集,然后针对 MongoDB Node.js 驱动程序执行这些命令。

Features (特性)

SQL to MongoDB Translation Examples (SQL 到 MongoDB 转换示例)

QueryLeaf 将 SQL 查询转换为 MongoDB 命令。 以下是一些转换示例:

Basic SELECT with WHERE (带有 WHERE 的基本 SELECT)

SQL:

SELECT name, email FROM users WHERE age > 21

MongoDB:

db.collection('users').find(
 { age: { $gt: 21 } },
 { name: 1, email: 1 }
)

Nested Field Access (嵌套字段访问)

SQL:

SELECT name, address.city, address.zip FROM users WHERE address.city = 'New York'

MongoDB:

db.collection('users').find(
 { 'address.city': 'New York' },
 { name: 1, 'address.city': 1, 'address.zip': 1 }
)

Array Element Access (数组元素访问)

SQL:

SELECT _id, items[0].name, items[0].price FROM orders WHERE items[0].price > 1000

MongoDB:

db.collection('orders').find(
 { 'items.0.price': { $gt: 1000 } },
 { _id: 1, 'items.0.name': 1, 'items.0.price': 1 }
)

GROUP BY with Aggregation (带有聚合函数的 GROUP BY)

SQL:

SELECT status, COUNT(*) as count, SUM(total) as total_amount FROM orders GROUP BY status

MongoDB:

db.collection('orders').aggregate([
 {
  $group: {
   _id: "$status",
   status: { $first: "$status" },
   count: { $sum: 1 },
   total_amount: { $sum: "$total" }
  }
 }
])

JOIN Between Collections (集合之间的 JOIN)

SQL:

SELECT u.name, o._id as order_id, o.total FROM users u JOIN orders o ON u._id = o.userId

MongoDB:

db.collection('users').aggregate([
 {
  $lookup: {
   from: "orders",
   localField: "_id",
   foreignField: "userId",
   as: "orders"
  }
 },
 { $unwind: { path: "$orders", preserveNullAndEmptyArrays: true } },
 {
  $project: {
   name: 1,
   order_id: "$orders._id",
   total: "$orders.total"
  }
 }
])

Installation (安装)

npm install @queryleaf/lib

Usage (用法)

QueryLeaf 接受现有的 MongoDB 客户端。 它永远不会自行创建或管理 MongoDB 连接。

import { QueryLeaf } from '@queryleaf/lib';
import { MongoClient } from 'mongodb';
// Your existing MongoDB client
const mongoClient = new MongoClient('mongodb://localhost:27017');
await mongoClient.connect();
// Create QueryLeaf with your MongoDB client
const queryLeaf = new QueryLeaf(mongoClient, 'mydatabase');
// Execute SQL queries against your MongoDB database
const results = await queryLeaf.execute('SELECT * FROM users WHERE age > 21');
console.log(results);
// When you're done, close your MongoDB client
// (QueryLeaf never manages MongoDB connections)
await mongoClient.close();

Testing with DummyQueryLeaf (使用 DummyQueryLeaf 进行测试)

为了在没有真实数据库的情况下进行测试或调试,请使用 DummyQueryLeaf:

import { DummyQueryLeaf } from '@queryleaf/lib';
// Create a DummyQueryLeaf instance for testing
const queryLeaf = new DummyQueryLeaf('mydatabase');
// Operations will be logged to console but not executed
await queryLeaf.execute('SELECT * FROM users WHERE age > 21');
// [DUMMY MongoDB] FIND in mydatabase.users with filter: { "age": { "$gt": 21 }}
// [DUMMY MongoDB] Executing find on users

Examples (示例)

该仓库包含几个示例:

您可以使用以下命令运行这些示例:

# Main application example
ts-node src/examples/existing-client-demo.ts
# Basic usage example
npm run example
# Dummy client example
ts-node src/examples/dummy-client-demo.ts

SQL Query Examples (SQL 查询示例)

以下是一些可以与 QueryLeaf 一起使用的实际 SQL 查询:

Working with Nested Fields (使用嵌套字段)

-- Query users by nested address field
SELECT name, email, address.city FROM users WHERE address.zip = '10001'
-- Insert with nested document structure
INSERT INTO users (name, age, email, address) VALUES
('Jane Smith', 28, 'jane@example.com', {
 "street": "456 Park Ave",
 "city": "Chicago",
 "state": "IL",
 "zip": "60601"
})
-- Update a nested field
UPDATE users SET address.city = 'San Francisco', address.state = 'CA' WHERE _id = '123'

Working with Array Fields (使用数组字段)

-- Query by array element property
SELECT userId, total FROM orders WHERE items[0].name = 'Laptop'
-- Filter by array element condition
SELECT * FROM orders WHERE items[1].price < 50
-- Insert document with array field
INSERT INTO orders (userId, items, status) VALUES
('user123', [
 { "id": "prod1", "name": "Monitor", "price": 300 },
 { "id": "prod2", "name": "Keyboard", "price": 75 }
], 'pending')

Advanced Queries (高级查询)

-- Using GROUP BY with aggregation functions
SELECT category, COUNT(*) as count, AVG(price) as avg_price FROM products GROUP BY category
-- JOIN between users and orders
SELECT u.name, o.total, o.status FROM users u JOIN orders o ON u._id = o.userId WHERE o.total > 100

查看 examples folder 获取更完整的示例,包括如何设置 QueryLeaf 实例并执行这些查询。

这个库演示了:

Architecture (架构)

QueryLeaf 遵循模块化架构:

  1. SqlParser:使用 node-sql-parser 将 SQL 文本转换为抽象语法树 (AST)
  2. SqlCompiler:将 AST 转换为 MongoDB 命令
  3. CommandExecutor:针对 MongoDB 数据库执行这些命令

Development (开发)

Testing (测试)

该项目包括单元测试和集成测试:

Unit Tests (单元测试)

使用以下命令运行单元测试:

npm run test:unit

单元测试位于 tests/unit 目录中,侧重于测试 SQL 语句的解析和编译,而无需数据库连接。

Integration Tests (集成测试)

集成测试使用 testcontainers 在 Docker 中启动 MongoDB 实例。 在执行这些测试之前,请确保已安装并运行 Docker。

使用以下命令运行集成测试:

npm run test:integration

集成测试位于 tests/integration 目录中,并使用真实的 MongoDB 数据库测试完整的功能。

这些测试将:

  1. 启动 MongoDB 容器
  2. 加载fixture数据
  3. 针对数据库运行一系列 SQL 查询
  4. 验证结果
  5. 完成后清理容器

要运行所有测试:

npm run test

Continuous Integration (持续集成)

本项目使用 GitHub Actions 进行持续集成。 CI 工作流程在以下情况下自动运行:

CI 工作流程:

  1. 设置 Node.js(版本 16.x、18.x 和 20.x)
  2. 安装依赖项
  3. 运行单元测试
  4. 在 Docker 容器中使用 MongoDB 运行集成测试
  5. 执行类型检查
  6. 构建软件包

您可以在 .github/workflows/test.yml 中看到工作流程配置。

Documentation (文档)

详细文档可在 queryleaf.com/docs 找到,包括:

对于本地开发,您可以使用以下命令运行文档站点:

# Install required packages
pip install -r requirements.txt
# Serve the documentation locally
npm run docs:serve

License (许可证)

QueryLeaf 采用双重许可:

有关商业许可选项和定价,请访问 queryleaf.com 或通过 info@queryleaf.com 与我们联系。

About

SQL for Mongo (in Node JS) queryleaf.com

Topics

nodejs typescript sql mongodb compiler

Resources

Readme

License

View license

Code of conduct

Code of conduct

Security policy

Security policy Activity Custom properties

Stars

19 stars

Watchers

1 watching

Forks

0 forks Report repository

Releases 5

Release 0.2.3 Latest May 3, 2025 + 4 releases

Packages 0

No packages published

Contributors 2

Languages

Footer

© 2025 GitHub, Inc.

Footer navigation

You can’t perform that action at this time.