Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

新增了OR和AND等选项 #83

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 70 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
ali-rds
=======
# ali-rds

[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
Expand Down Expand Up @@ -30,14 +29,14 @@ Support `MySQL`, `SQL Server` and `PostgreSQL`.
### Create RDS instance

```js
const rds = require('ali-rds');
const rds = require("ali-rds");

const db = rds({
host: 'your-rds-address.mysql.rds.aliyuncs.com',
host: "your-rds-address.mysql.rds.aliyuncs.com",
port: 3306,
user: 'your-username',
password: 'your-password',
database: 'your-database-name',
user: "your-username",
password: "your-password",
database: "your-database-name",

// optional params
// The charset for the connection.
Expand Down Expand Up @@ -160,7 +159,7 @@ console.log(result);

### Update multiple rows

- Update multiple rows with primary key: `id`
- Update multiple rows with primary key: `id`

```js
let options = [{
Expand Down Expand Up @@ -188,8 +187,7 @@ console.log(result);
changedRows: 2 }
```

- Update multiple rows with `row` and `where` properties

- Update multiple rows with `row` and `where` properties

```js
let options = [{
Expand All @@ -207,7 +205,7 @@ let options = [{
email: 'm@fengmk2_2.com',
otherField: 'other field value2',
modifiedAt: db.literals.now, // `now()` on db server
},
},
where: {
id: 124,
name: 'fengmk2_2',
Expand All @@ -225,7 +223,6 @@ console.log(result);
changedRows: 2 }
```


### Get

- Get a row
Expand Down Expand Up @@ -261,6 +258,54 @@ let rows = yield db.select('table-name', {
WHERE `type` = 'javascript' ORDER BY `id` DESC
```

- 复杂查询
> 如果你看到这里说明你和我遇到了一样的问题,egg/mysql 缺少一些实用方法,这里做了一些扩展,可能在你的使用过程中,还会存在 bug,请参考着继续完善吧。

```js
let rows = yield db.select('table-name', {
where: {
sender: { op: 'like', value: `%111%` },
receiver: { op: 'like', value: `%222%` },
cn_orderno_list: { op: 'like', value: `%333%` },
OR: {
sender11: { op: 'like', value: `%111%` },
receiver22: { op: 'like', value: `%222%` },
},
a: 1,
b: [11, 22],
AND: {
orderno: null,
id: 1,
role: ['admin', 'guest'],
OR: {
realname: { op: 'like', value: 'simba' },
age: { op: '>', value: '20' },
nickname: { op: 'like', value: 'ace' }
},
createtime: [
{ op: '>', value: '2020-10-13' },
{ op: '<', value: '2020-11-22' },
]
},
},
columns: ['author', 'title'],
orders: [['id', 'desc']]
});

=> SELECT * FROM `t_order`
WHERE `sender` like '%111%'
AND `receiver` like '%222%'
AND `cn_orderno_list` like '%333%'
AND (`sender11` like '%111%' OR `receiver22` like '%222%')
AND `a` = 1
AND `b` IN (11, 22)
AND (`orderno` IS NULL AND `id` = 1
AND `role` IN ('admin', 'guest')
AND (`realname` like 'simba' OR `age` > '20' OR `nickname` like 'ace')
AND (`createtime` > '2020-10-13' AND `createtime` < '2020-11-22')
)
```

### Delete

- Delete with condition
Expand Down Expand Up @@ -337,7 +382,7 @@ function* foo(ctx, data1) {
function* bar(ctx, data2) {
return yield db.beginTransactionScope(function* (conn) {
// execute foo with the same transaction scope
yield foo(ctx, { foo: 'bar' });
yield foo(ctx, { foo: "bar" });
yield conn.insert(table2, data2);
return { success: true };
}, ctx);
Expand Down Expand Up @@ -379,20 +424,20 @@ TBD

### IO queries

- *query(sql[, values)
- *queryOne(sql[, values)
- *select(table, options)
- *get(table, where, options)
- *insert(table, row[s], options)
- *update(table, row, options)
- *updateRows(table, options)
- *delete(table, where)
- *count(table, where)
- \*query(sql[, values)
- \*queryOne(sql[, values)
- \*select(table, options)
- \*get(table, where, options)
- \*insert(table, row[s], options)
- \*update(table, row, options)
- \*updateRows(table, options)
- \*delete(table, where)
- \*count(table, where)

#### Transactions

- *beginTransaction()
- *beginTransactionScope(scope)
- \*beginTransaction()
- \*beginTransactionScope(scope)

### Utils

Expand All @@ -416,7 +461,7 @@ INSERT INTO `user` SET `name` = 'fengmk2', `createdAt` = now()
#### Custom Literal

```js
let session = new db.literals.Literal('session()');
let session = new db.literals.Literal("session()");
```

## TODO
Expand Down
105 changes: 66 additions & 39 deletions lib/operator.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,25 @@ module.exports = Operator;
/**
* Operator Interface
*/
function Operator() {}
function Operator() { }

const proto = Operator.prototype;

proto.literals = literals;

proto.escape = function(value, stringifyObjects, timeZone) {
proto.escape = function (value, stringifyObjects, timeZone) {
return SqlString.escape(value, stringifyObjects, timeZone);
};

proto.escapeId = function(value, forbidQualified) {
proto.escapeId = function (value, forbidQualified) {
return SqlString.escapeId(value, forbidQualified);
};

proto.format = function(sql, values, stringifyObjects, timeZone) {
proto.format = function (sql, values, stringifyObjects, timeZone) {
// if values is object, not null, not Array;
if (!Array.isArray(values) && typeof values === 'object' && values !== null) {
// object not support replace column like ??;
return sql.replace(/\:(\w+)/g, function(txt, key) {
return sql.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return SqlString.escape(values[key]);
}
Expand All @@ -45,7 +45,7 @@ proto.format = function(sql, values, stringifyObjects, timeZone) {
};

proto.query = function* (sql, values) {
// query(sql, values)
console.log(sql);
if (arguments.length >= 2) {
sql = this.format(sql, values);
}
Expand All @@ -66,12 +66,12 @@ proto.queryOne = function* (sql, values) {
return rows && rows[0] || null;
};

proto._query = function(/* sql */) {
proto._query = function (/* sql */) {
throw new Error('SubClass must impl this');
};

proto.count = function* (table, where) {
const sql = this.format('SELECT COUNT(*) as count FROM ??', [ table ]) +
const sql = this.format('SELECT COUNT(*) as count FROM ??', [table]) +
this._where(where);
debug('count(%j, %j) \n=> %j', table, where, sql);
const rows = yield this.query(sql);
Expand Down Expand Up @@ -118,13 +118,13 @@ proto.insert = function* (table, rows, options) {
} else {
// insert(table, row)
firstObj = rows;
rows = [ rows ];
rows = [rows];
}
if (!options.columns) {
options.columns = Object.keys(firstObj);
}

const params = [ table, options.columns ];
const params = [table, options.columns];
const strs = [];
for (let i = 0; i < rows.length; i++) {
const values = [];
Expand Down Expand Up @@ -163,7 +163,7 @@ proto.update = function* (table, row, options) {
values.push(column);
values.push(row[column]);
}
const sql = this.format('UPDATE ?? SET ', [ table ]) +
const sql = this.format('UPDATE ?? SET ', [table]) +
this.format(sets.join(', '), values) +
this._where(options.where);
debug('update(%j, %j, %j) \n=> %j', table, row, options, sql);
Expand Down Expand Up @@ -252,8 +252,8 @@ proto.updateRows = function* (table, options) {
}
});

let SQL = [ 'UPDATE ?? SET ' ];
let VALUES = [ table ];
let SQL = ['UPDATE ?? SET '];
let VALUES = [table];

const TEMPLATE = [];
for (const key in SQL_CASE) {
Expand Down Expand Up @@ -299,59 +299,86 @@ proto.updateRows = function* (table, options) {
};

proto.delete = function* (table, where) {
const sql = this.format('DELETE FROM ??', [ table ]) +
const sql = this.format('DELETE FROM ??', [table]) +
this._where(where);
debug('delete(%j, %j) \n=> %j', table, where, sql);
return yield this.query(sql);
};

proto._where = function(where) {
if (!where) {
return '';
}
proto._where = function (where) {
if (!where || !Object.keys(where).length) return '';
return ' WHERE ' + fakeWhere.call(this, where)
}

function fakeWhere(where, op = ' AND ') {
if (!where) return '';
const wheres = [];
const values = [];
for (const key in where) {
const value = where[key];
if (Array.isArray(value)) {
wheres.push('?? IN (?)');
} else {
if (value === null || value === undefined) {
wheres.push('?? IS ?');
} else {
wheres.push('?? = ?');
}
let val = where[key];
switch (key) {
case 'OR':
case 'AND':
wheres.push(`(${fakeWhere.call(this, val, ` ${key} `)})`)
break;
default:
if (Array.isArray(val)) {
//type:[1,2]
if (['string', 'number'].includes(typeof val[0])) {
wheres.push(`?? IN (?)`)
} else {
//createtime: [
// { op: '>', value: '2020-10-13' },
// { op: '<', value: '2020-11-22' },
//]
let rr = []
val.forEach(r => {
rr.push(`?? ${r.op} ?`)
values.push(key);
values.push(r.value);
})
wheres.push(`(${rr.join(' AND ')})`);
}
} else {
// orderid:null
if (val === null || val === undefined)
wheres.push(`?? IS ?`)
// a:{op:'>',value:'2020'}
else if (val && val.op)
wheres.push(`?? ${val.op} ?`)
//a:1
else
wheres.push(`?? = ?`)
}
values.push(key);
//有带运算的条件,拼接value
if (val && val.op) values.push(val.value)
else values.push(val);
}
values.push(key);
values.push(value);
}
if (wheres.length > 0) {
return this.format(' WHERE ' + wheres.join(' AND '), values);
}
return '';

return wheres.length > 0 ? this.format(wheres.join(op), values) : '';
};

proto._selectColumns = function(table, columns) {
proto._selectColumns = function (table, columns) {
if (!columns) {
columns = '*';
}
let sql;
if (columns === '*') {
sql = this.format('SELECT * FROM ??', [ table ]);
sql = this.format('SELECT * FROM ??', [table]);
} else {
sql = this.format('SELECT ?? FROM ??', [ columns, table ]);
sql = this.format('SELECT ?? FROM ??', [columns, table]);
}
return sql;
};

proto._orders = function(orders) {
proto._orders = function (orders) {
if (!orders) {
return '';
}
if (typeof orders === 'string') {
orders = [ orders ];
orders = [orders];
}
const values = [];
for (let i = 0; i < orders.length; i++) {
Expand All @@ -374,7 +401,7 @@ proto._orders = function(orders) {
return ' ORDER BY ' + values.join(', ');
};

proto._limit = function(limit, offset) {
proto._limit = function (limit, offset) {
if (!limit || typeof limit !== 'number') {
return '';
}
Expand Down