1.0.1 • Published 9 months ago

obj-2-sql v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

Obj-2-SQL 项目介绍

项目背景

在软件开发中,对象与关系数据库之间的数据转换一直是一个挑战。传统的 ORM(对象关系映射)工具虽然在一定程度上解决了这个问题,但往往伴随着复杂的配置和性能瓶颈。Obj-2-SQL 项目致力于提供一个轻量级、高性能的解决方案,使开发者能够更专注于业务逻辑的实现,而不是繁琐的数据访问层代码。

使用文档

导入模块

import { getWhereQuerys, getSelectSql } from 'obj-2-sql';

示例代码

// 示例对象
const conditions = [
  { field: 'name', type: '=', value: 'bob' },
  { field: 'age', type: '>', value: 18 }
];

// 生成 WHERE 查询
const whereQuery = getWhereQuerys(conditions);
console.log(whereQuery);

输出结果

`name` = 'bob' AND `age` > 18

完整示例

const selectSql = getSelectSql({
  table: 'order_detail',
  fields: [
    { field: 'product_id', table: 'order_detail' },
    { field: 'product_count', table: 'order_detail', aggType: 'SUM', alias: 'total_count' },
    { field: 'product_name', table: 'product' }
  ],
  where: [{ field: { field: 'product_id', table: 'order_detail' }, type: '>', value: 1 }],
  join: [
    {
      table: 'product',
      on: [
        { table: 'order_detail', field: 'product_id' },
        { table: 'product', field: 'id' }
      ],
      type: 'LEFT'
    }
  ],
  group: {
    field: [
      { field: 'product_id', table: 'order_detail' },
      { field: 'product_name', table: 'product' }
    ],
    having: [{ field: { table: 'order_detail', field: 'product_id' }, type: '>', value: 1 }]
  },
  page: { page: 3, pageSize: 20 }
});
console.log(selectSql);

输出结果

SELECT
    `order_detail`.`product_id`,
    SUM(`order_detail`.`product_count`) AS `total_count`,
    `product`.`product_name`
FROM
    `order_detail`
    LEFT JOIN `product` ON `order_detail`.`product_id` = `product`.`id`
WHERE
    `order_detail`.`product_id` > 1
GROUP BY
    `order_detail`.`product_id`,
    `product`.`product_name`
HAVING
    `order_detail`.`product_id` > 1
LIMIT
    40, 20

防注入示例

getWhereQuerys([
      { field: 'name', type: 'IN', value: ['bob', 'alice'] },
      { field: 'name2', type: 'NOT IN', value: [`bob' OR 1=1 --`, 'alice'] }
    ]);
// 返回: `name` IN ('bob','alice') AND `name2` NOT IN ('bob\\' OR 1=1 --','alice'

getWhereQuerys([
         { field: 'name', type: '=', value: "bob' OR 1=1 --" },
         { field: 'age', type: "> 1' OR 1=1 --" as unknown as any, value: 18 }
       ]);
// 报错: 不支持的条件类型:> 1' OR 1=1 --

getSelectSql({
        table: 'order',
        join: {
          table: 'order_detail',
          on: [
            { table: 'order', field: 'id' },
            { table: 'order_detail', field: 'order_id' }
          ],
          type: "LEFT'; select * from order_detail; --" as unknown as 'LEFT'
        },
        limit: 10
      });
// 报错: Join类型错误, 只支持LEFT, RIGHT, INNER
1.0.1

9 months ago

1.0.0

9 months ago

0.1.3

9 months ago

0.1.2

9 months ago

0.1.1

9 months ago

0.1.0

9 months ago

0.0.5

9 months ago

0.0.4

9 months ago

0.0.3

9 months ago

0.0.2

9 months ago

0.0.1

9 months ago