Vona ORM分表全攻略

分表

针对高并发、数据量大的场景,通常会考虑采用分表机制进行优化。下面以 Model User/Order 为例,通过查询用户的订单列表,来演示分表的使用方法

分表规则

比如需要对订单表进行分表操作。可以根据实际业务需求设计分表规则,在这里,根据用户Id取模动态生成表名。比如,拆分为16张表,用户Id129,对应的表名如下:

typescript 复制代码
const tableName = `Order_${129 % 16}`;  // Order_1

准备Models

先准备两个 Models:User/Order

  1. Model Order
typescript 复制代码
@Model({
  entity: EntityOrder,
})
class ModelOrder{}
  1. Model User
typescript 复制代码
@Model({
  entity: EntityUser,
  relations: {
    orders: $relation.hasMany(() => ModelOrder, 'userId'),
  },
})
class ModelUser {}

查询数据

1. 直接查询订单列表

typescript 复制代码
class ServiceOrder {
  async selectOrdersDirectly() {
    const userId = 129;
    const orders = await this.scope.model.order.select({
      where: {
        userId,
      },
    });
  }
}  

到目前为止,使用默认表名查询userId=129的订单列表

2. 基于关系查询订单列表

typescript 复制代码
class ServiceOrder {
  async selectOrdersByRelation() {
    const userId = 129;
    const userAndOrders = await this.scope.model.user.get({
      id: userId,
    }, {
      include: {
        orders: true,
      },
    });
  }
}  

到目前为止,使用默认表名查询userId=129的用户信息,使用默认表名查询该用户的订单列表

使用分表:动态方式

可以在代码中动态使用分表:

diff 复制代码
class ServiceOrder {
  async selectOrdersDirectly() {
    const userId = 129;
+   const tableName = `Order_${userId % 16}`;
+   const modelOrder = this.scope.model.order.newInstance(undefined, tableName as any);
    const orders = await modelOrder.select({
      where: {
        userId,
      },
    });
  }
}  
  • newInstance: 传入要使用的表名,返回新的 Model 实例

到目前为止,使用分表查询userId=129的订单列表

使用分表:Relation动态选项

可以在 relation 选项中动态指定表名:

diff 复制代码
class ServiceOrder {
  async selectOrdersByRelation() {
    const userId = 129;
+   const tableName = `Order_${userId % 16}`;
    const userAndOrders = await this.scope.model.user.get({
      id: userId,
    }, {
      include: {
        orders: {
+         meta: {
+           table: tableName as any,
+         },
        },
      },
    });
  }
}  
  • meta.table: 指定 relation orders要使用的表名

到目前为止,使用默认表名查询userId=129的用户信息,使用分表查询该用户的订单列表

使用分表:Model配置

也可以直接在 Model 中配置分表规则,从而简化查询代码

  1. Model Order
diff 复制代码
@Model({
  entity: EntityOrder,
+ table(_ctx: VonaContext, where: EntityOrder | undefined, defaultTable: keyof ITableRecord) {
+   const userId = where?.userId;
+   if (!userId) return defaultTable;
+   return `Order_${Number(userId) % 16}`;
+ },
})
class ModelOrder{}
  • table: 指定函数,实现分表规则
  1. 查询数据

现在,又可以使用常规的方式查询用户的订单列表

typescript 复制代码
class ServiceOrder {
  async selectOrdersDirectly() {
    const userId = 129;
    const orders = await this.scope.model.order.select({
      where: {
        userId,
      },
    });
  }
}  
typescript 复制代码
class ServiceOrder {
  async selectOrdersByRelation() {
    const userId = 129;
    const userAndOrders = await this.scope.model.user.get({
      id: userId,
    }, {
      include: {
        orders: true,
      },
    });
  }
}  

使用分表:App Config配置

也可以在 App config 中配置 Model options:

src/backend/config/config/config.ts

typescript 复制代码
// onions
config.onions = {
  model: {
    'test-vona:order': {
      table(_ctx: VonaContext, where: EntityOrder | undefined, defaultTable: keyof ITableRecord) {
        const userId = where?.userId;
        if (!userId) return defaultTable;
        return `Order_${Number(userId) % 16}`;
      },
    },
  },
};

于是,也可以使用常规的方式查询用户的订单列表

使用分表:Relation静态选项

也可以在定义 Relation 时指定静态选项:

diff 复制代码
@Model({
  entity: EntityUser,
  relations: {
    orders: $relation.hasMany(() => ModelOrder, 'userId', {
+     meta: {
+       table(_ctx: VonaContext, where: EntityOrder | undefined, defaultTable: keyof ITableRecord) {
+         const userId = where?.userId;
+         if (!userId) return defaultTable;
+         return `Order_${Number(userId) % 16}`;
+       },
+     },
    }),
  },
})
class ModelUser {}

同样,也可以使用常规的方式查询用户的订单列表

Vona ORM已开源:github.com/vonajs/vona

相关推荐
竹林8181 小时前
在Web3前端用Node.js子进程批量校验钱包,我踩了这些性能与安全的坑
javascript·node.js
oyzz1209 小时前
Windows 上彻底卸载 Node.js
windows·node.js
MIka9 小时前
CopilotKit 入门:用 Runtime 和 React Core 搭建真正可用的 AI Copilot
人工智能·typescript·agent
小霍同学9 小时前
Node.js 起步指南
node.js
学以智用9 小时前
# TypeScript 高级特性(核心+实用)
前端·javascript·typescript
学以智用9 小时前
TypeScript 核心基础:类型/变量 + 函数 + 接口
前端·javascript·typescript
蕨类植物9 小时前
Fastify 模块化项目实战(二) — 初始化Fastify 项目
typescript
蕨类植物9 小时前
Fastify 模块化项目实战 - 你真的懂 tsconfig.json 吗?
typescript
codingWhat10 小时前
用 Express 简单Mock自助终端机读取身份证
node.js·express
We་ct10 小时前
LeetCode 74. 搜索二维矩阵:两种高效解题思路
前端·算法·leetcode·矩阵·typescript·二分查找