/**
* SQL where 条件构建器
*/
export default class CreateSqlWhere {
/**
* where 条件 sql
*/
whereSql: string;
getSql() {
return this.whereSql;
}
eq(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} = '${value}'`;
return this;
}
ne(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} != '${value}'`;
return this;
}
gt(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} > '${value}'`;
return this;
}
ge(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} >= '${value}'`;
return this;
}
lt(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} < '${value}'`;
return this;
}
le(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} <= '${value}'`;
return this;
}
like(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} like '%${value}'%`;
return this;
}
likeLeft(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} like '%${value}'`;
return this;
}
likeRight(field?: string, value?: string) {
this.defConnect();
this.whereSql += `${field} like '${value}'%`;
return this;
}
in(field?: string, values?: Array<any>) {
if (values.length > 0) {
this.defConnect();
let sql = `${field} in (`;
for (let i = 0; i < values.length; i++) {
if (i === values.length - 1) {
sql += `'${values[i]}'`;
} else {
sql += `'${values[i]}', `;
}
}
sql += ')';
this.whereSql += sql;
}
return this;
}
notIn(field?: string, values?: Array<any>) {
if (values.length > 0) {
this.defConnect();
let sql = `${field} not in (`;
for (let i = 0; i < values.length; i++) {
if (i === values.length - 1) {
sql += `'${values[i]}'`;
} else {
sql += `'${values[i]}', `;
}
}
sql += ')';
this.whereSql += sql;
}
return this;
}
or() {
if (this.whereSql) {
this.whereSql += ' or ';
} else {
this.whereSql = '';
}
return this;
}
private defConnect() {
if (this.whereSql) {
if (!this.whereSql.endsWith('and ') && !this.whereSql.endsWith('or ')) {
this.whereSql += ' and ';
}
} else {
this.whereSql = '';
}
}
}
测试用例
const where = new CreateSqlWhere().eq('test', '001')
.in('test1', [1001, 1002, 1003])
.eq('test2', '001')
.or()
.in('test3', [1001, 1002, 1003])
.getSql();