Skip to content

Commit

Permalink
closes #75 Filtering a relation
Browse files Browse the repository at this point in the history
  • Loading branch information
lroal committed Mar 15, 2024
1 parent 443cc8a commit c07011d
Show file tree
Hide file tree
Showing 48 changed files with 511 additions and 239 deletions.
10 changes: 8 additions & 2 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,14 @@
"vscode": {
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"dbaeumer.vscode-eslint"
]
"dbaeumer.vscode-eslint",
"adpyke.vscode-sql-formatter"
],
"settings": {
"[sql]": {
"editor.defaultFormatter": "adpyke.vscode-sql-formatter"
}
}
}
},
// "workspaceMount": "source=${localWorkspaceFolder}/sub-folder,target=/workspace,type=bind",
Expand Down
25 changes: 23 additions & 2 deletions src/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ function rdbClient(options = {}) {
}

async function getManyCore() {
let args = Array.prototype.slice.call(arguments);
let args = negotiateWhere.apply(null, arguments);
let body = stringify({
path: 'getManyDto',
args
Expand All @@ -275,6 +275,27 @@ function rdbClient(options = {}) {
return adapter.post(body);
}

function negotiateWhere(_, strategy, ...rest) {
const args = Array.prototype.slice.call(arguments);
if (strategy)
return [_, where(strategy), ...rest];
else
return args;
}

function where(_strategy, path = '') {
if (typeof _strategy !== 'object')
return _strategy;
const strategy = { ..._strategy };
for (let name in _strategy) {
if (name === 'where' && typeof strategy[name] === 'function')
strategy.where = column(path + 'where')(strategy.where);
else
strategy[name] = where(_strategy[name], path + name + '.');
}
return strategy;
}

async function _delete() {
let args = Array.prototype.slice.call(arguments);
let body = stringify({
Expand Down Expand Up @@ -349,7 +370,7 @@ function rdbClient(options = {}) {

async function insertAndForget(rows) {
const concurrency = undefined;
let args = [concurrency, {insertAndForget: true}];
let args = [concurrency, { insertAndForget: true }];
if (Array.isArray(rows)) {
let proxy = proxify([], args[0]);
proxy.splice.apply(proxy, [0, 0, ...rows]);
Expand Down
25 changes: 23 additions & 2 deletions src/client/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5562,7 +5562,7 @@ function rdbClient(options = {}) {
}

async function getManyCore() {
let args = Array.prototype.slice.call(arguments);
let args = negotiateWhere.apply(null, arguments);
let body = stringify({
path: 'getManyDto',
args
Expand All @@ -5571,6 +5571,27 @@ function rdbClient(options = {}) {
return adapter.post(body);
}

function negotiateWhere(_, strategy, ...rest) {
const args = Array.prototype.slice.call(arguments);
if (strategy)
return [_, where(strategy), ...rest];
else
return args;
}

function where(_strategy, path = '') {
if (typeof _strategy !== 'object')
return _strategy;
const strategy = { ..._strategy };
for (let name in _strategy) {
if (name === 'where' && typeof strategy[name] === 'function')
strategy.where = column(path + 'where')(strategy.where);
else
strategy[name] = where(_strategy[name], path + name + '.');
}
return strategy;
}

async function _delete() {
let args = Array.prototype.slice.call(arguments);
let body = stringify({
Expand Down Expand Up @@ -5645,7 +5666,7 @@ function rdbClient(options = {}) {

async function insertAndForget(rows) {
const concurrency = undefined;
let args = [concurrency, {insertAndForget: true}];
let args = [concurrency, { insertAndForget: true }];
if (Array.isArray(rows)) {
let proxy = proxify([], args[0]);
proxy.splice.apply(proxy, [0, 0, ...rows]);
Expand Down
4 changes: 4 additions & 0 deletions src/getManyDto.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ const newForeignKeyFilter = require('./table/relation/newForeignKeyFilter');

async function getManyDto(table, filter, strategy) {
filter = negotiateRawSqlFilter(filter, table);
if (strategy && strategy.where) {
let arg = typeof strategy.where === 'function' ? strategy.where(table) : strategy.where;
filter = filter.and(arg);
}
let span = strategyToSpan(table, strategy);
let alias = table._dbName;

Expand Down
13 changes: 3 additions & 10 deletions src/getManyDto/query/newSingleQuery.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,19 @@
var newColumnSql = require('../../table/query/singleQuery/newColumnSql');
var newWhereSql = require('../../table/query/singleQuery/newWhereSql');
var newJoinSql = require('../../table/query/singleQuery/newJoinSql');

var newParameterized = require('../../table/query/newParameterized');

function _new(table,filter,span, alias,orderBy,limit,offset) {
var c = {};

var name = table._dbName;
var columnSql = newColumnSql(table,span,alias,true);
var joinSql = newJoinSql(span,alias);
var joinSql = newJoinSql(span, alias);
var whereSql = newWhereSql(table,filter,alias);
if (limit)
limit = limit + ' ';

return newParameterized('select ' + limit + columnSql + ' from ' + name + ' ' + alias).append(joinSql).append(whereSql).append(orderBy + offset);

c.sql = function() {
return 'select ' + limit + columnSql + ' from ' + name + ' ' + alias + joinSql + whereSql + orderBy + offset;
};

c.parameters = filter.parameters;

return c;
}

module.exports = _new;
12 changes: 10 additions & 2 deletions src/getTSDefinition.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ function getTSDefinition(tableConfigs, {isNamespace = false, isHttp = false} = {
}

function getTable(table, Name, name, customFilters) {
const _columns = columns(table);
const _tableRelations = tableRelations(table);
return `
export interface ${Name}Table {
count(filter?: RawFilter): Promise<number>;
Expand Down Expand Up @@ -76,8 +78,13 @@ export interface ${Name}Table {
patch(patch: JsonPatch): Promise<void>;
patch(patch: JsonPatch, concurrency: ${Name}Concurrency, fetchingStrategy?: ${Name}Strategy): Promise<void>;
customFilters: ${Name}CustomFilters;
${columns(table)}
${tableRelations(table)}
${_columns}
${_tableRelations}
}
export interface ${Name}TableBase {
${_columns}
${_tableRelations}
}
export interface ${Name}ExpressConfig {
Expand Down Expand Up @@ -223,6 +230,7 @@ export interface ${name}Strategy {
limit?: number;
offset?: number;
orderBy?: Array<${orderByColumns(table)}> | ${orderByColumns(table)};
where?: (table: ${name}TableBase) => RawFilter;
}
${otherConcurrency}
Expand Down
29 changes: 26 additions & 3 deletions src/hostExpress/executePath.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ let _allowedOps = {
exists: true,
all: true,
any: true,
none: true
none: true,
where: true,
};

async function executePath({ table, JSONFilter, baseFilter, customFilters = {}, request, response, readonly, disableBulkDeletes, isHttp, client }) {
Expand All @@ -67,9 +68,11 @@ async function executePath({ table, JSONFilter, baseFilter, customFilters = {},
function parseFilter(json, table) {
if (isFilter(json)) {
let subFilters = [];

let anyAllNone = tryGetAnyAllNone(json.path, table);
if (anyAllNone) {

if (isHttp)
validateArgs(json.args[0]);
const f = anyAllNone(x => parseFilter(json.args[0], x));
f.isSafe = isSafe;
return f;
Expand All @@ -96,7 +99,7 @@ async function executePath({ table, JSONFilter, baseFilter, customFilters = {},
table = table[path[i]];
}

let ops = new Set(['all', 'any', 'none']);
let ops = new Set(['all', 'any', 'none', 'where']);
let last = path.slice(-1)[0];
if (ops.has(last) || (table && (table._primaryColumns || (table.any && table.all))))
return table;
Expand Down Expand Up @@ -129,6 +132,7 @@ async function executePath({ table, JSONFilter, baseFilter, customFilters = {},
for (let i = 0; i < pathArray.length; i++) {
target = target[pathArray[i]];
}

let res = target.apply(null, args);
setSafe(res);
return res;
Expand Down Expand Up @@ -251,16 +255,33 @@ async function executePath({ table, JSONFilter, baseFilter, customFilters = {},
if (_baseFilter)
filter = filter.and(_baseFilter);
let args = [filter].concat(Array.prototype.slice.call(arguments).slice(1));
await negotiateWhere(strategy);
return table.getManyDto.apply(null, args);
}

async function negotiateWhere(strategy) {
if (typeof strategy !== 'object')
return;

for(let name in strategy) {
if(name === 'where') {
// validateArgs(strategy);
strategy.where = await parseFilter(strategy[name], table);
}
else
await negotiateWhere(strategy[name]);
}

}

async function getMany(filter, strategy) {
validateStrategy(table, strategy);
filter = negotiateFilter(filter);
const _baseFilter = await invokeBaseFilter();
if (_baseFilter)
filter = filter.and(_baseFilter);
let args = [filter].concat(Array.prototype.slice.call(arguments).slice(1));
await negotiateWhere(strategy);
return table.getMany.apply(null, args);
}

Expand Down Expand Up @@ -335,6 +356,7 @@ function validateArgs() {
}
if (Array.isArray(filter))
for (let i = 0; i < filter.length; i++) {

validateArgs(filter[i]);
}
}
Expand All @@ -350,6 +372,7 @@ function setSafe(o) {
Object.defineProperty(o, 'isSafe', {
value: isSafe,
enumerable: false

});
}

Expand Down
1 change: 1 addition & 0 deletions src/map.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,7 @@ type FetchingStrategy<T> = {
| OrderBy<Extract<keyof AllowedColumns<T>, string>>;
limit?: number;
offset?: number;
where?: (table: MappedColumnsAndRelations<T>) => RawFilter;
};

type ColumnConcurrency = {
Expand Down
2 changes: 1 addition & 1 deletion src/mssql/newTransaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function newResolveTransaction(domain, pool) {
}
client.setUseUTC(false);
client.executeQuery = wrapQuery(client);
rdb.engine = 'mssql';
rdb.engine = 'mssqlNative';
rdb.dbClient = client;
rdb.dbClientDone = done;
rdb.encodeBoolean = encodeBoolean;
Expand Down
8 changes: 0 additions & 8 deletions src/oracle/newInsertCommandCore.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,8 @@ function newInsertCommandCore(table, row, options = {}) {
}
}

//todo
//add outParams
//result.resultFromOutParams = true;
//result.outParamsLength = 2;
var sql = util.format.apply(null, values);
return newParameterized(sql, parameters);
}

module.exports = newInsertCommandCore;

// INSERT INTO _order (orderDate,customerId) OUTPUT INSERTED.id,INSERTED.orderDate,INSERTED.customerId VALUES (@0,1)
// parameters: 0,[object Object],'2022-01-11T09:24:47.000'

3 changes: 3 additions & 0 deletions src/table.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ var patchTable = require('./patchTable');
var newEmitEvent = require('./emitEvent');
var hostLocal = require('./hostLocal');
var getTSDefinition = require('./getTSDefinition');
var where = require('./table/where');

function _new(tableName) {
var table = newContext();
Expand Down Expand Up @@ -157,6 +158,8 @@ function _new(tableName) {
return getTSDefinition(table, {name});
};

table.where = where(table);

return table;
}

Expand Down
2 changes: 1 addition & 1 deletion src/table/column/extractAlias.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
function extract(table, optionalAlias) {
if (optionalAlias)
return optionalAlias;
return table._dbName;
return table._rootAlias || table._dbName;
}

module.exports = extract;
2 changes: 1 addition & 1 deletion src/table/commands/delete/singleCommand/joinSql.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function newJoinSql(relations) {
function addSql(relation) {
var rightColumns = relation.childTable._primaryColumns;
var leftColumns = relation.columns;
sql += ' INNER' + newShallowJoinSql(relation.childTable,leftColumns,rightColumns,leftAlias,rightAlias);
sql += ' INNER' + newShallowJoinSql(relation.childTable,leftColumns,rightColumns,leftAlias,rightAlias).sql();
}

relations.forEach(function(relation, i){
Expand Down
5 changes: 3 additions & 2 deletions src/table/commands/delete/singleCommand/whereSql.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ function newWhereSql(relations, shallowFilter, rightAlias) {
var table = relation.childTable;
var joinCore = newShallowJoinSql(table, leftColumns, rightColumns, leftAlias, rightAlias);
if (shallowFilter.sql())
sql = shallowFilter.prepend(' WHERE ' + joinCore + ' AND ');
sql = shallowFilter.prepend(' AND ').prepend(joinCore).prepend(' WHERE ');
else
sql = ' WHERE ' + joinCore;
sql = joinCore.prepend(' WHERE ');
}

return sql;
}

Expand Down
10 changes: 1 addition & 9 deletions src/table/commands/newInsertCommandCore.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,8 @@ function newInsertCommandCore(table, row, options = {}) {
}
}

//todo
//add outParams
//result.resultFromOutParams = true;
//result.outParamsLength = 2;
var sql = util.format.apply(null, values);
return newParameterized(sql, parameters);
}

module.exports = newInsertCommandCore;

// INSERT INTO _order (orderDate,customerId) OUTPUT INSERTED.id,INSERTED.orderDate,INSERTED.customerId VALUES (@0,1)
// parameters: 0,[object Object],'2022-01-11T09:24:47.000'

module.exports = newInsertCommandCore;
13 changes: 3 additions & 10 deletions src/table/count.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,11 @@ async function count(table, filter) {

function newQuery(table, filter, alias) {
filter = extractFilter(filter);
var name = table._dbName;
var whereSql = newWhereSql(table, filter, alias);

let c = {};
c.sql = function() {
var name = table._dbName;
var whereSql = newWhereSql(table, filter, alias);
return whereSql.prepend('select count(*) "_count" from ' + name + ' ' + alias);

return 'select count(*) "_count" from ' + name + ' ' + alias + whereSql;
};

c.parameters = filter.parameters;

return c;

}

Expand Down
Loading

0 comments on commit c07011d

Please sign in to comment.