0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2024-12-16 20:26:19 -05:00

Optmize adapter upsert query

This commit is contained in:
Gao Sun 2021-06-26 01:48:02 +08:00
parent b892c882be
commit 65cd21377c
No known key found for this signature in database
GPG key ID: 0F0EFA2E36639F31

View file

@ -17,6 +17,11 @@ export default function postgresAdapter(modelName: string) {
type QueryResult = Pick<OidcModelInstanceDBEntry, 'payload' | 'consumedAt'>; type QueryResult = Pick<OidcModelInstanceDBEntry, 'payload' | 'consumedAt'>;
const convertResult = (result: QueryResult | null) => const convertResult = (result: QueryResult | null) =>
conditional(result && withConsumed(result.payload, result.consumedAt)); conditional(result && withConsumed(result.payload, result.consumedAt));
const setExcluded = (...fields: IdentifierSqlTokenType[]) =>
sql.join(
fields.map((field) => sql`${field}=excluded.${field}`),
sql`, `
);
const findByField = async <T extends ValueExpressionType>( const findByField = async <T extends ValueExpressionType>(
field: IdentifierSqlTokenType, field: IdentifierSqlTokenType,
@ -57,12 +62,13 @@ export default function postgresAdapter(modelName: string) {
${payload.grantId ?? null} ${payload.grantId ?? null}
) )
on conflict (${fields.modelName}, ${fields.id}) do update on conflict (${fields.modelName}, ${fields.id}) do update
set set ${setExcluded(
${fields.payload}=excluded.${fields.payload}, fields.payload,
${fields.expiresAt}=excluded.${fields.expiresAt}, fields.expiresAt,
${fields.userCode}=excluded.${fields.userCode}, fields.userCode,
${fields.uid}=excluded.${fields.uid}, fields.uid,
${fields.grantId}=excluded.${fields.grantId} fields.grantId
)}
`); `);
}, },
find: async (id) => findByField(fields.id, id), find: async (id) => findByField(fields.id, id),