语法指南
lite-ibatis 使用缩进式语法(类似 Pug),通过缩进来表示代码块的层级关系。
基本规则
- 使用空格或制表符缩进(不能混用)
- 建议每级缩进使用 2 个空格
- 换行表示新语句开始
- 缩进增加表示子块开始,缩进减少表示子块结束
SQL 块定义
使用 $id: 定义一个命名的 SQL 块:
$getUser:
select * from users
where id = #{id}一个模板中可以定义多个块:
$insert:
insert into users (name, age) values (#{name}, #{age})
$update:
update users set name = #{name} where id = #{id}
$delete:
delete from users where id = #{id}参数替换
#{param} - 预编译参数
生成 ? 占位符,值放入 params 数组,防止 SQL 注入:
输入: select * from users where id = #{id}
数据: { id: 123 }
输出: select * from users where id = ?
参数: [123]${param} - 字符串插值
直接替换为 data.param 的值,适用于表名、字段名等:
输入: select * from ${table} where id = #{id}
数据: { table: 'users', id: 123 }
输出: select * from users where id = ?
参数: [123]条件块 #if
当 data.condition 为真值时,子内容才会被包含:
$getUser:
select * from users
#if name
where name = #{name}
#if age
and age = #{age}typescript
// 传入 { name: '张三', age: 25 }
// 输出:
// select * from users
// where name = ?
// and age = ?
// 传入 {}
// 输出:
// select * from users嵌套条件
$complex:
select * from users
#if active
where status = 'active'
#if role
and role = #{role}注释
单行注释 //
$getUser:
// 这是单行注释
select * from users多行注释 //.
$getUser:
//.
这是多行注释
可以跨越多行
通过缩进控制范围
select * from users脚本
单行脚本 -
$getUser:
- var table = 'users'
select * from ${table}多行脚本 -.
$getUser:
-.
var table = 'users'
var columns = ['id', 'name', 'age']
select ${columns.join(', ')} from ${table}预留语法(待实现)
#in - 循环
$batchInsert:
insert into users values
#in user in users
(#{user.id}, #{user.name})#include - 包含其他模板
$getUser:
#include $commonSelect
from users