QueryLeaf: SQL for Mongo
QueryLeaf:用于 Mongo 的 SQL 查询引擎
Navigation Menu(导航菜单,此处省略,原文中均为站内链接)
beekeeper-studio / queryleaf Public
- Notifications You must be signed in to change notification settings
- Fork 0
- Star 19
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
用于 NodeJS 的 SQL 到 MongoDB 查询转换器
Overview (概述)
QueryLeaf 是一个将 SQL 查询转换为 MongoDB 命令的库。 它使用 node-sql-parser 解析 SQL,将其转换为抽象命令集,然后针对 MongoDB Node.js 驱动程序执行这些命令。
Features (特性)
- 使用 node-sql-parser 将 SQL 语句解析为抽象语法树
- 将 SQL AST 编译为 MongoDB 命令
- 使用官方驱动程序执行 MongoDB 命令
- 支持基本 SQL 操作:
- SELECT
- INSERT
- UPDATE
- DELETE
- 高级查询功能:
- 嵌套字段访问(例如,
address.zip
) - 数组元素访问(例如,
items[0].name
) - 带有聚合函数的 GROUP BY(COUNT、SUM、AVG、MIN、MAX)
- 集合之间的 JOIN
- 嵌套字段访问(例如,
- 多种接口:
- 用于直接集成到代码中的库
- 用于命令行 SQL 查询的 CLI
- 用于 REST API 访问的 Web 服务器
- PostgreSQL Wire Protocol Server 用于连接标准 PostgreSQL 客户端
SQL to MongoDB Translation Examples (SQL 到 MongoDB 转换示例)
QueryLeaf 将 SQL 查询转换为 MongoDB 命令。 以下是一些转换示例:
Basic SELECT with WHERE (带有 WHERE 的基本 SELECT)
SELECT name, email FROM users WHERE age > 21
MongoDB:
db.collection('users').find(
{ age: { $gt: 21 } },
{ name: 1, email: 1 }
)
Nested Field Access (嵌套字段访问)
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 (数组元素访问)
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)
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)
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 (示例)
src/examples/existing-client-demo.ts
- 展示了如何在实际应用程序中使用 QueryLeafsrc/examples/basic-usage.ts
- 演示了使用现有 MongoDB 客户端的基本用法src/examples/dummy-client-demo.ts
- 展示了如何使用 DummyQueryLeaf 进行测试
您可以使用以下命令运行这些示例:
# 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 实例并执行这些查询。
这个库演示了:
- 基本 SELECT 查询
- 使用 WHERE 子句进行过滤
- 使用 ORDER BY 进行排序
- INSERT、UPDATE 和 DELETE 操作
- 使用点表示法访问嵌套字段
- 使用索引访问数组元素
- 使用 GROUP BY 和聚合函数进行聚合
- 使用 JOIN 语法连接集合
Architecture (架构)
- SqlParser:使用 node-sql-parser 将 SQL 文本转换为抽象语法树 (AST)
- SqlCompiler:将 AST 转换为 MongoDB 命令
- 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 数据库测试完整的功能。
这些测试将:
- 启动 MongoDB 容器
- 加载fixture数据
- 针对数据库运行一系列 SQL 查询
- 验证结果
- 完成后清理容器
要运行所有测试:
npm run test
Continuous Integration (持续集成)
本项目使用 GitHub Actions 进行持续集成。 CI 工作流程在以下情况下自动运行:
- 所有推送到
main
分支的操作 - 所有以
main
分支为目标的pull request
CI 工作流程:
- 设置 Node.js(版本 16.x、18.x 和 20.x)
- 安装依赖项
- 运行单元测试
- 在 Docker 容器中使用 MongoDB 运行集成测试
- 执行类型检查
- 构建软件包
您可以在 .github/workflows/test.yml
中看到工作流程配置。
Documentation (文档)
详细文档可在 queryleaf.com/docs 找到,包括:
- 详细的安装和设置指南
- 支持的 SQL 语法的深入解释
- 用法示例和最佳实践
- 故障排除和调试指南
- 性能优化技巧
对于本地开发,您可以使用以下命令运行文档站点:
# Install required packages
pip install -r requirements.txt
# Serve the documentation locally
npm run docs:serve
License (许可证)
- AGPL-3.0 用于开源使用
- Commercial license 用于嵌入的商业用途
有关商业许可选项和定价,请访问 queryleaf.com 或通过 info@queryleaf.com 与我们联系。
About
SQL for Mongo (in Node JS) queryleaf.com
Topics
nodejs typescript sql mongodb compiler
Resources
License
Code of conduct
Security policy
Security policy Activity Custom properties
Stars
Watchers
Forks
Releases 5
Release 0.2.3 Latest May 3, 2025 + 4 releases
Packages 0
No packages published
Contributors 2
Languages
Footer
Footer navigation
You can’t perform that action at this time.