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

fix: Case Sensitive Quoted Column Names Support for Context.DB #448

Closed
wants to merge 3 commits into from
Closed
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
Binary file added runner/src/.DS_Store
Binary file not shown.
105 changes: 98 additions & 7 deletions runner/src/dml-handler/dml-handler.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable quote-props */
import pgFormat from 'pg-format';
import DmlHandler from './dml-handler';

Expand Down Expand Up @@ -39,7 +40,7 @@ describe('DML Handler tests', () => {

await dmlHandler.insert(SCHEMA, TABLE_NAME, [inputObj]);
expect(query.mock.calls).toEqual([
['INSERT INTO test_schema."test_table" (account_id, block_height, block_timestamp, content, receipt_id, accounts_liked) VALUES (\'test_acc_near\', \'999\', \'UTC\', \'test_content\', \'111\', \'["cwpuzzles.near","devbose.near"]\') RETURNING *', []]
['INSERT INTO test_schema."test_table" ("account_id", "block_height", "block_timestamp", "content", "receipt_id", "accounts_liked") VALUES (\'test_acc_near\', \'999\', \'UTC\', \'test_content\', \'111\', \'["cwpuzzles.near","devbose.near"]\') RETURNING *', []]
]);
});

Expand All @@ -59,7 +60,27 @@ describe('DML Handler tests', () => {

await dmlHandler.insert(SCHEMA, TABLE_NAME, inputObj);
expect(query.mock.calls).toEqual([
['INSERT INTO test_schema."test_table" (account_id, block_height, receipt_id) VALUES (\'morgs_near\', \'1\', \'abc\'), (\'morgs_near\', \'2\', \'abc\') RETURNING *', []]
['INSERT INTO test_schema."test_table" ("account_id", "block_height", "receipt_id") VALUES (\'morgs_near\', \'1\', \'abc\'), (\'morgs_near\', \'2\', \'abc\') RETURNING *', []]
]);
});

test('Test valid insert with mix of quoted columns', async () => {
const inputObj = [{
'account_id': 'morgs_near',
block_height: 1,
'receipt_id': 'abc',
},
{
account_id: 'morgs_near',
'block_height': 2,
receipt_id: 'abc',
}];

const dmlHandler = await DmlHandler.create(ACCOUNT, hasuraClient, PgClient);

await dmlHandler.insert(SCHEMA, TABLE_NAME, inputObj);
expect(query.mock.calls).toEqual([
['INSERT INTO test_schema."test_table" ("account_id", "block_height", "receipt_id") VALUES (\'morgs_near\', \'1\', \'abc\'), (\'morgs_near\', \'2\', \'abc\') RETURNING *', []]
]);
});

Expand All @@ -73,7 +94,7 @@ describe('DML Handler tests', () => {

await dmlHandler.select(SCHEMA, TABLE_NAME, inputObj);
expect(query.mock.calls).toEqual([
['SELECT * FROM test_schema."test_table" WHERE account_id=$1 AND block_height=$2', Object.values(inputObj)]
['SELECT * FROM test_schema."test_table" WHERE "account_id"=$1 AND "block_height"=$2', Object.values(inputObj)]
]);
});

Expand All @@ -87,7 +108,21 @@ describe('DML Handler tests', () => {

await dmlHandler.select(SCHEMA, TABLE_NAME, inputObj, 1);
expect(query.mock.calls).toEqual([
['SELECT * FROM test_schema."test_table" WHERE account_id=$1 AND block_height=$2 LIMIT 1', Object.values(inputObj)]
['SELECT * FROM test_schema."test_table" WHERE "account_id"=$1 AND "block_height"=$2 LIMIT 1', Object.values(inputObj)]
]);
});

test('Test valid select on two fields with limit and quoted column', async () => {
const inputObj = {
account_id: 'test_acc_near',
'block_height': 999,
};

const dmlHandler = await DmlHandler.create(ACCOUNT, hasuraClient, PgClient);

await dmlHandler.select(SCHEMA, TABLE_NAME, inputObj, 1);
expect(query.mock.calls).toEqual([
['SELECT * FROM test_schema."test_table" WHERE "account_id"=$1 AND "block_height"=$2 LIMIT 1', Object.values(inputObj)]
]);
});

Expand All @@ -106,7 +141,26 @@ describe('DML Handler tests', () => {

await dmlHandler.update(SCHEMA, TABLE_NAME, whereObj, updateObj);
expect(query.mock.calls).toEqual([
['UPDATE test_schema."test_table" SET content=$1, receipt_id=$2 WHERE account_id=$3 AND block_height=$4 RETURNING *', [...Object.values(updateObj), ...Object.values(whereObj)]]
['UPDATE test_schema."test_table" SET "content"=$1, "receipt_id"=$2 WHERE "account_id"=$3 AND "block_height"=$4 RETURNING *', [...Object.values(updateObj), ...Object.values(whereObj)]]
]);
});

test('Test valid update on two fields with mixed quotes', async () => {
const whereObj = {
'account_id': 'test_acc_near',
block_height: 999,
};

const updateObj = {
content: 'test_content',
'receipt_id': 111,
};

const dmlHandler = await DmlHandler.create(ACCOUNT, hasuraClient, PgClient);

await dmlHandler.update(SCHEMA, TABLE_NAME, whereObj, updateObj);
expect(query.mock.calls).toEqual([
['UPDATE test_schema."test_table" SET "content"=$1, "receipt_id"=$2 WHERE "account_id"=$3 AND "block_height"=$4 RETURNING *', [...Object.values(updateObj), ...Object.values(whereObj)]]
]);
});

Expand All @@ -129,7 +183,30 @@ describe('DML Handler tests', () => {

await dmlHandler.upsert(SCHEMA, TABLE_NAME, inputObj, conflictCol, updateCol);
expect(query.mock.calls).toEqual([
['INSERT INTO test_schema."test_table" (account_id, block_height, receipt_id) VALUES (\'morgs_near\', \'1\', \'abc\'), (\'morgs_near\', \'2\', \'abc\') ON CONFLICT (account_id, block_height) DO UPDATE SET receipt_id = excluded.receipt_id RETURNING *', []]
['INSERT INTO test_schema."test_table" ("account_id", "block_height", "receipt_id") VALUES (\'morgs_near\', \'1\', \'abc\'), (\'morgs_near\', \'2\', \'abc\') ON CONFLICT ("account_id", "block_height") DO UPDATE SET "receipt_id" = excluded."receipt_id" RETURNING *', []]
]);
});

test('Test valid upsert on two fields with mixed quotes', async () => {
const inputObj = [{
account_id: 'morgs_near',
'block_height': 1,
receipt_id: 'abc'
},
{
'account_id': 'morgs_near',
block_height: 2,
receipt_id: 'abc'
}];

const conflictCol = ['account_id', 'block_height'];
const updateCol = ['receipt_id'];

const dmlHandler = await DmlHandler.create(ACCOUNT, hasuraClient, PgClient);

await dmlHandler.upsert(SCHEMA, TABLE_NAME, inputObj, conflictCol, updateCol);
expect(query.mock.calls).toEqual([
['INSERT INTO test_schema."test_table" ("account_id", "block_height", "receipt_id") VALUES (\'morgs_near\', \'1\', \'abc\'), (\'morgs_near\', \'2\', \'abc\') ON CONFLICT ("account_id", "block_height") DO UPDATE SET "receipt_id" = excluded."receipt_id" RETURNING *', []]
]);
});

Expand All @@ -143,7 +220,21 @@ describe('DML Handler tests', () => {

await dmlHandler.delete(SCHEMA, TABLE_NAME, inputObj);
expect(query.mock.calls).toEqual([
['DELETE FROM test_schema."test_table" WHERE account_id=$1 AND block_height=$2 RETURNING *', Object.values(inputObj)]
['DELETE FROM test_schema."test_table" WHERE "account_id"=$1 AND "block_height"=$2 RETURNING *', Object.values(inputObj)]
]);
});

test('Test valid delete on two fields with quoted column', async () => {
const inputObj = {
account_id: 'test_acc_near',
'block_height': 999,
};

const dmlHandler = await DmlHandler.create(ACCOUNT, hasuraClient, PgClient);

await dmlHandler.delete(SCHEMA, TABLE_NAME, inputObj);
expect(query.mock.calls).toEqual([
['DELETE FROM test_schema."test_table" WHERE "account_id"=$1 AND "block_height"=$2 RETURNING *', Object.values(inputObj)]
]);
});
});
46 changes: 32 additions & 14 deletions runner/src/dml-handler/dml-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,24 @@ export default class DmlHandler {
return [];
}

tableName = addQuotes(tableName);

const keys = Object.keys(objects[0]);
const quotedKeys = keys.map(key => addQuotes(key));
// Get array of values from each object, and return array of arrays as result. Expects all objects to have the same number of items in same order
const values = objects.map(obj => keys.map(key => obj[key]));
const query = `INSERT INTO ${schemaName}."${tableName}" (${keys.join(', ')}) VALUES %L RETURNING *`;
const query = `INSERT INTO ${schemaName}.${tableName} (${quotedKeys.join(', ')}) VALUES %L RETURNING *`;

const result = await wrapError(async () => await this.pgClient.query(this.pgClient.format(query, values), []), `Failed to execute '${query}' on ${schemaName}."${tableName}".`);
return result.rows;
}

async select (schemaName: string, tableName: string, object: any, limit: number | null = null): Promise<any[]> {
const keys = Object.keys(object);
tableName = addQuotes(tableName);
const quotedKeys = Object.keys(object).map(key => addQuotes(key));
const values = Object.values(object);
const param = Array.from({ length: keys.length }, (_, index) => `${keys[index]}=$${index + 1}`).join(' AND ');
let query = `SELECT * FROM ${schemaName}."${tableName}" WHERE ${param}`;
const param = Array.from({ length: quotedKeys.length }, (_, index) => `${quotedKeys[index]}=$${index + 1}`).join(' AND ');
let query = `SELECT * FROM ${schemaName}.${tableName} WHERE ${param}`;
if (limit !== null) {
query = query.concat(' LIMIT ', Math.round(limit).toString());
}
Expand All @@ -54,13 +58,14 @@ export default class DmlHandler {
}

async update (schemaName: string, tableName: string, whereObject: any, updateObject: any): Promise<any[]> {
const updateKeys = Object.keys(updateObject);
const updateParam = Array.from({ length: updateKeys.length }, (_, index) => `${updateKeys[index]}=$${index + 1}`).join(', ');
const whereKeys = Object.keys(whereObject);
const whereParam = Array.from({ length: whereKeys.length }, (_, index) => `${whereKeys[index]}=$${index + 1 + updateKeys.length}`).join(' AND ');
tableName = addQuotes(tableName);
const quotedUpdateKeys = Object.keys(updateObject).map(key => addQuotes(key));
const updateParam = Array.from({ length: quotedUpdateKeys.length }, (_, index) => `${quotedUpdateKeys[index]}=$${index + 1}`).join(', ');
const quotedWhereKeys = Object.keys(whereObject).map(key => addQuotes(key));
const whereParam = Array.from({ length: quotedWhereKeys.length }, (_, index) => `${quotedWhereKeys[index]}=$${index + 1 + quotedUpdateKeys.length}`).join(' AND ');

const queryValues = [...Object.values(updateObject), ...Object.values(whereObject)];
const query = `UPDATE ${schemaName}."${tableName}" SET ${updateParam} WHERE ${whereParam} RETURNING *`;
const query = `UPDATE ${schemaName}.${tableName} SET ${updateParam} WHERE ${whereParam} RETURNING *`;

const result = await wrapError(async () => await this.pgClient.query(this.pgClient.format(query), queryValues), `Failed to execute '${query}' on ${schemaName}."${tableName}".`);
return result.rows;
Expand All @@ -70,24 +75,37 @@ export default class DmlHandler {
if (!objects?.length) {
return [];
}

const keys = Object.keys(objects[0]);

tableName = addQuotes(tableName);
conflictColumns = conflictColumns.map(key => addQuotes(key));
updateColumns = updateColumns.map(key => addQuotes(key));
const quotedKeys = keys.map(key => addQuotes(key));

// Get array of values from each object, and return array of arrays as result. Expects all objects to have the same number of items in same order
const values = objects.map(obj => keys.map(key => obj[key]));
const updatePlaceholders = updateColumns.map(col => `${col} = excluded.${col}`).join(', ');
const query = `INSERT INTO ${schemaName}."${tableName}" (${keys.join(', ')}) VALUES %L ON CONFLICT (${conflictColumns.join(', ')}) DO UPDATE SET ${updatePlaceholders} RETURNING *`;
const query = `INSERT INTO ${schemaName}.${tableName} (${quotedKeys.join(', ')}) VALUES %L ON CONFLICT (${conflictColumns.join(', ')}) DO UPDATE SET ${updatePlaceholders} RETURNING *`;

const result = await wrapError(async () => await this.pgClient.query(this.pgClient.format(query, values), []), `Failed to execute '${query}' on ${schemaName}."${tableName}".`);
return result.rows;
}

async delete (schemaName: string, tableName: string, object: any): Promise<any[]> {
const keys = Object.keys(object);
tableName = addQuotes(tableName);
const quotedKeys = Object.keys(object).map(key => addQuotes(key));
const values = Object.values(object);
const param = Array.from({ length: keys.length }, (_, index) => `${keys[index]}=$${index + 1}`).join(' AND ');
const query = `DELETE FROM ${schemaName}."${tableName}" WHERE ${param} RETURNING *`;
const param = Array.from({ length: quotedKeys.length }, (_, index) => `${quotedKeys[index]}=$${index + 1}`).join(' AND ');
const query = `DELETE FROM ${schemaName}.${tableName} WHERE ${param} RETURNING *`;

const result = await wrapError(async () => await this.pgClient.query(this.pgClient.format(query), values), `Failed to execute '${query}' on ${schemaName}."${tableName}".`);
return result.rows;
}
}

function addQuotes (key: string): string {
if (key.startsWith('"') && key.endsWith('"')) {
return key;
}
return `"${key}"`;
}
13 changes: 7 additions & 6 deletions runner/src/indexer/indexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ export default class Indexer {
return pascalCaseTableName;
}

buildDatabaseContext (account: string, schemaName: string, schema: string, blockHeight: number): Record<string, Record<string, (...args: any[]) => any>> {
buildDatabaseContext (functionName: string, schemaName: string, schema: string, blockHeight: number): Record<string, Record<string, (...args: any[]) => any>> {
const account = functionName.split('/')[0].replace(/[.-]/g, '_');
try {
const tables = this.getTableNames(schema);
const sanitizedTableNames = new Set<string>();
Expand All @@ -235,7 +236,7 @@ export default class Indexer {
[`${sanitizedTableName}`]: {
insert: async (objectsToInsert: any) => {
// Write log before calling insert
await this.writeLog(`context.db.${sanitizedTableName}.insert`, blockHeight, defaultLog + '.insert',
await this.writeLog(functionName, blockHeight, defaultLog + '.insert',
`Inserting object ${JSON.stringify(objectsToInsert)} into table ${tableName} on schema ${schemaName}`);

// Wait for initialiiation of DmlHandler
Expand All @@ -246,7 +247,7 @@ export default class Indexer {
},
select: async (filterObj: any, limit = null) => {
// Write log before calling select
await this.writeLog(`context.db.${sanitizedTableName}.select`, blockHeight, defaultLog + '.select',
await this.writeLog(functionName, blockHeight, defaultLog + '.select',
`Selecting objects with values ${JSON.stringify(filterObj)} in table ${tableName} on schema ${schemaName} with ${limit === null ? 'no' : limit} limit`);

// Wait for initialiiation of DmlHandler
Expand All @@ -257,7 +258,7 @@ export default class Indexer {
},
update: async (filterObj: any, updateObj: any) => {
// Write log before calling update
await this.writeLog(`context.db.${sanitizedTableName}.update`, blockHeight, defaultLog + '.update',
await this.writeLog(functionName, blockHeight, defaultLog + '.update',
`Updating objects that match ${JSON.stringify(filterObj)} with values ${JSON.stringify(updateObj)} in table ${tableName} on schema ${schemaName}`);

// Wait for initialiiation of DmlHandler
Expand All @@ -268,7 +269,7 @@ export default class Indexer {
},
upsert: async (objectsToInsert: any, conflictColumns: string[], updateColumns: string[]) => {
// Write log before calling upsert
await this.writeLog(`context.db.${sanitizedTableName}.upsert`, blockHeight, defaultLog + '.upsert',
await this.writeLog(functionName, blockHeight, defaultLog + '.upsert',
`Inserting objects with values ${JSON.stringify(objectsToInsert)} into table ${tableName} on schema ${schemaName}. Conflict on columns ${conflictColumns.join(', ')} will update values in columns ${updateColumns.join(', ')}`);

// Wait for initialiiation of DmlHandler
Expand All @@ -279,7 +280,7 @@ export default class Indexer {
},
delete: async (filterObj: any) => {
// Write log before calling delete
await this.writeLog(`context.db.${sanitizedTableName}.delete`, blockHeight, defaultLog + '.delete',
await this.writeLog(functionName, blockHeight, defaultLog + '.delete',
`Deleting objects with values ${JSON.stringify(filterObj)} from table ${tableName} on schema ${schemaName}`);

// Wait for initialiiation of DmlHandler
Expand Down