Skip to content

Commit

Permalink
fetch related column
Browse files Browse the repository at this point in the history
  • Loading branch information
Lars-Erik Roald committed May 8, 2024
1 parent 1e51239 commit 4a43fff
Show file tree
Hide file tree
Showing 9 changed files with 135 additions and 24 deletions.
22 changes: 21 additions & 1 deletion src/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,7 @@ function tableProxy() {
}

function aggregate(path, arg) {

const c = {
sum,
count,
Expand All @@ -815,7 +816,26 @@ function aggregate(path, arg) {
min
};

return arg(c);
let handler = {
get(_target, property,) {
if (property in c)
return Reflect.get(...arguments);
else {
subColumn = column(path + 'aggregate');
return column(property);
}
}

};
let subColumn;
const proxy = new Proxy(c, handler);

const result = arg(proxy);

if (subColumn)
return subColumn(result.self());
else
return result;


function sum(fn) {
Expand Down
4 changes: 3 additions & 1 deletion src/getManyDto.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,9 @@ async function decode(strategy, span, rows, keys = rows.length > 0 ? Object.keys
}

for (let j = 0; j < aggregateKeys.length; j++) {
outRow[aggregateKeys[j]] = Number.parseFloat(row[keys[j+columnsLength]]);
const key = aggregateKeys[j];
const parse = span.aggregates[key].column?.decode || Number.parseFloat;
outRow[key] = parse(row[keys[j+columnsLength]]);
}

outRows[i] = outRow;
Expand Down
3 changes: 2 additions & 1 deletion src/hostExpress/executePath.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ let _allowedOps = {
max: true,
min: true,
count: true,
aggregate: true
aggregate: true,
self: true,
};

async function executePath({ table, JSONFilter, baseFilter, customFilters = {}, request, response, readonly, disableBulkDeletes, isHttp, client }) {
Expand Down
1 change: 1 addition & 0 deletions src/table.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var hostLocal = require('./hostLocal');
var getTSDefinition = require('./getTSDefinition');
var where = require('./table/where');
var aggregate = require('./table/aggregate');
var subColumn = require('./table/aggregate');

function _new(tableName) {
var table = newContext();
Expand Down
10 changes: 10 additions & 0 deletions src/table/column/newColumn.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,16 @@ module.exports = function(table, name) {
c.le = c.lessThanOrEqual;
c.LE = c.le;
c.IN = c.in;
c.self = self;

function self() {
const tableAlias = table._rootAlias || table._dbName;
return {
expression: (alias) => `${tableAlias}.${c._dbName} ${alias}`,
join: '',
column: c
};
}

return c;
};
61 changes: 61 additions & 0 deletions src/table/relatedTable/childColumn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
var newJoin = require('./joinSql');
var getSessionContext = require('../getSessionContext');
var newJoinCore = require('../query/singleQuery/joinSql/newShallowJoinSqlCore');

function childColumn(column, relations) {
const context = getSessionContext();
const outerAlias = 'y' + context.aggregateCount++;
const alias = 'x' + relations.length;
const foreignKeys = getForeignKeys(relations[0]);
const select = ` LEFT JOIN (SELECT ${foreignKeys},${alias}.${column._dbName} as prop`;
const innerJoin = relations.length > 1 ? newJoin(relations).sql() : '';
const onClause = createOnClause(relations[0], outerAlias);
const from = ` FROM ${relations.at(-1).childTable._dbName} ${alias} ${innerJoin}) ${outerAlias} ON (${onClause})`;
const join = select + from ;

return {
//todo
expression: (alias) => `${outerAlias}.prop ${alias}`,
join,
column
};
}

function createOnClause(relation, rightAlias) {
var c = {};
var sql = '';
let leftAlias = relation.parentTable._rootAlias || relation.parentTable._dbName;

c.visitJoin = function(relation) {
sql = newJoinCore(relation.childTable,relation.columns,relation.childTable._primaryColumns,leftAlias,rightAlias).sql();
};

c.visitOne = function(relation) {
innerJoin(relation);
};

c.visitMany = c.visitOne;

function innerJoin(relation) {
var joinRelation = relation.joinRelation;
var childTable = relation.childTable;
var parentTable = relation.parentTable;
var columns = joinRelation.columns;

sql = newJoinCore(childTable,parentTable._primaryColumns,columns,leftAlias, rightAlias).sql();
}
relation.accept(c);
return sql;
}

function getForeignKeys(relation) {
let columns;
let alias = 'x1';
if (relation.joinRelation)
columns = relation.joinRelation.columns;
else
columns = relation.childTable._primaryColumns;
return columns.map(x => `${alias}.${x._dbName}`).join(',');
}

module.exports = childColumn;
2 changes: 2 additions & 0 deletions src/table/relatedTable/relatedColumn.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var newSubFilter = require('./subFilter');
var aggregate = require('./columnAggregate');
var childColumn = require('./childColumn');

function newRelatedColumn(column, relations, isShallow, depth) {
var c = {};
Expand All @@ -17,6 +18,7 @@ function newRelatedColumn(column, relations, isShallow, depth) {
c.min = aggregate.bind(null, 'min', column, relations);
c.max = aggregate.bind(null, 'max', column, relations);
c.count = aggregate.bind(null, 'count', column, relations);
c.self = childColumn.bind(null, column, relations);

return c;

Expand Down
2 changes: 1 addition & 1 deletion src/table/strategyToSpan.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function toSpan(table,strategy) {
addLeg(legs,table,strategy,name);
else if (table[name] && table[name].eq)
columns.set(table[name], strategy[name]);
else if (strategy[name]?.expression && strategy[name]?.join)
else if (strategy[name]?.expression && (strategy[name]?.join || strategy[name]?.column))
span.aggregates[name] = strategy[name];
else
span[name] = strategy[name];
Expand Down
54 changes: 34 additions & 20 deletions tests/getMany.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -513,16 +513,24 @@ describe('getMany with aggregates', () => {
async function verify(dbName) {
const { db } = getDb(dbName);
const rows = await db.order.getAll({
where: x => x.customer.name.notEqual(null),
customerName: x => x.customer.name,
id2: x => x.id,
lines: {
id2: x => x.id,
numberOfPackages: x => x.count(x => x.packages.id)
},
customer: {
bar: x => x.balance
},
postalPlace: x => x.deliveryAddress.postalPlace,
maxLines: x => x.max(x => x.lines.id),
numberOfPackages: x => x.count(x => x.lines.packages.id),
sumPackages: x => x.sum(x => x.lines.packages.id),
balance: x => x.min(x => x.customer.balance),
customerId2: x => x.sum(x => x.customer.id),
});
rows[0].

//mssql workaround because datetime has no time offset
for (let i = 0; i < rows.length; i++) {
rows[i].orderDate = dateToISOString(new Date(rows[i].orderDate));
Expand All @@ -533,6 +541,9 @@ rows[0].
const expected = [
{
id: 1,
id2: 1,
customerName: 'George',
postalPlace: 'Jakobsli',
orderDate: dateToISOString(date1),
customerId: 1,
maxLines: 2,
Expand All @@ -541,19 +552,22 @@ rows[0].
balance: 177,
customerId2: 1,
lines: [
{ product: 'Bicycle', id: 1, orderId: 1, numberOfPackages: 1 },
{ product: 'Small guitar', id: 2, orderId: 1, numberOfPackages: 1 }
]
// customer: {
// id: 1,
// name: 'George',
// balance: 177,
// isActive: true,
// bar: 177
// },
{ id2: 1, product: 'Bicycle', id: 1, orderId: 1, numberOfPackages: 1 },
{ id2: 2, product: 'Small guitar', id: 2, orderId: 1, numberOfPackages: 1 }
],
customer: {
id: 1,
name: 'George',
balance: 177,
isActive: true,
bar: 177
},
},
{
id: 2,
id2: 2,
customerName: 'Harry',
postalPlace: 'Surrey',
orderDate: dateToISOString(date2),
customerId: 2,
maxLines: 3,
Expand All @@ -562,15 +576,15 @@ rows[0].
balance: 200,
customerId2: 2,
lines: [
{ product: 'Magic wand', id: 3, orderId: 2, numberOfPackages: 1 }
]
// customer: {
// id: 2,
// name: 'Harry',
// balance: 200,
// isActive: true,
// bar: 200
// },
{ id2: 3, product: 'Magic wand', id: 3, orderId: 2, numberOfPackages: 1 }
],
customer: {
id: 2,
name: 'Harry',
balance: 200,
isActive: true,
bar: 200
},
}
];

Expand Down

0 comments on commit 4a43fff

Please sign in to comment.