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

chore(rethinkdb): Organization: Phase 2 #9931

Merged
merged 48 commits into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
bfa5c21
chore: read ReflectionGroups from PG
mattkrick May 29, 2024
7ac086e
Merge branch 'master' into chore/retrogroups3
mattkrick May 29, 2024
9844960
Merge branch 'master' into chore/retrogroups3
mattkrick May 30, 2024
62e123c
chore: add PG RetroReflection table
mattkrick May 30, 2024
c38f86c
chore: write to PG RetroReflection table
mattkrick Jun 3, 2024
d318560
fixup: inserts and updates
mattkrick Jun 4, 2024
16843dc
Merge branch 'master' into retroReflection-phase1e
mattkrick Jun 4, 2024
abb3bdf
fix: move to record literal types
mattkrick Jun 4, 2024
9911448
fix types
mattkrick Jun 4, 2024
af03b31
chore: migrate reflections to PG
mattkrick Jun 6, 2024
2a3c0ca
Merge branch 'master' into retroReflection-phase1e
mattkrick Jun 6, 2024
8dfa870
fix: remove hard delete of inactive groups
mattkrick Jun 6, 2024
3b48d22
Merge branch 'retroReflection-phase1e' into chore/retroReflection-phase2
mattkrick Jun 6, 2024
24da04b
fixup: remove unused var
mattkrick Jun 6, 2024
c60e502
Merge branch 'retroReflection-phase1e' into chore/retroReflection-phase2
mattkrick Jun 6, 2024
0d2c7d7
handle escape chars and commas
mattkrick Jun 6, 2024
9ef9346
chore: begin building equality checker
mattkrick Jun 6, 2024
76aeff9
fixup: account for lots of formatting in content
mattkrick Jun 7, 2024
0830c8e
Merge branch 'retroReflection-phase1e' into chore/retroReflection-phase2
mattkrick Jun 24, 2024
a12b08a
fix: rename extra spaces for conversion from plaintext to content
mattkrick Jun 24, 2024
a732657
fix: rename Reactji composite type attributes
mattkrick Jun 24, 2024
954503d
fix: constructor prop in lookup table
mattkrick Jun 25, 2024
c7775ad
handle reactji migration
mattkrick Jun 25, 2024
d53aca4
change dataloaders to pg
mattkrick Jun 25, 2024
6689e39
fix: self-review
mattkrick Jun 25, 2024
a6fd0d3
Merge branch 'master' into chore/retroReflection-phase2
mattkrick Jun 25, 2024
00964a8
Merge branch 'chore/retroReflection-phase2' into chore/retroReflectio…
mattkrick Jun 25, 2024
50ca56b
fix: migration order rename
mattkrick Jun 25, 2024
b220f22
Merge branch 'chore/retroReflection-phase2' into chore/retroReflectio…
mattkrick Jun 25, 2024
22ca4f3
chore: write to PG
mattkrick Jun 25, 2024
9c55acd
chore: migrate old records to PG
mattkrick Jun 25, 2024
9dfd35c
fix: add teamid FK
mattkrick Jun 25, 2024
654aa42
Merge branch 'chore/timeline-phase1' into chore/timeline-phase2
mattkrick Jun 25, 2024
ebbea29
chore: read from pg
mattkrick Jun 25, 2024
7dbea0d
Merge branch 'master' into chore/timeline-phase2
mattkrick Jun 26, 2024
3fd2236
Merge branch 'chore/timeline-phase2' into chore/timeline-phase3
mattkrick Jun 26, 2024
c552ea6
fix bad merge
mattkrick Jun 26, 2024
50d9e77
Merge branch 'chore/timeline-phase2' into chore/timeline-phase3
mattkrick Jun 26, 2024
b7c092d
add migration
mattkrick Jun 26, 2024
fe9efe9
write to pg
mattkrick Jun 27, 2024
4d838f3
Merge branch 'master' into chore/organization-phase1
mattkrick Jun 27, 2024
34b05bf
Merge branch 'master' into chore/organization-phase1
mattkrick Jul 1, 2024
02aa23d
Merge branch 'master' into chore/organization-phase1
mattkrick Jul 1, 2024
dfba81e
Merge branch 'master' into chore/organization-phase1
mattkrick Jul 1, 2024
81d68b7
Merge branch 'master' into chore/organization-phase1
mattkrick Jul 3, 2024
f4f5ede
fix: array append/remove
mattkrick Jul 3, 2024
dcbcd78
chore: migrate existing orgs to PG
mattkrick Jul 3, 2024
0a549d6
Merge branch 'master' into chore/organization-phase2
mattkrick Jul 4, 2024
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
55 changes: 30 additions & 25 deletions packages/server/graphql/private/mutations/checkRethinkPgEquality.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import getKysely from '../../../postgres/getKysely'
import {checkRowCount, checkTableEq} from '../../../postgres/utils/checkEqBase'
import {
compareDateAlmostEqual,
compareOptionalPlaintextContent,
compareRValOptionalPluckedArray,
compareRValOptionalPluckedObject,
compareRValStringAsNumber,
compareRValUndefinedAsEmptyArray,
compareRValUndefinedAsFalse,
compareRValUndefinedAsNull,
compareRValUndefinedAsNullAndTruncateRVal,
compareRealNumber,
compareRValUndefinedAsZero,
defaultEqFn
} from '../../../postgres/utils/rethinkEqualityFns'
import {MutationResolvers} from '../resolverTypes'
Expand All @@ -36,11 +37,11 @@ const checkRethinkPgEquality: MutationResolvers['checkRethinkPgEquality'] = asyn
) => {
const r = await getRethink()

if (tableName === 'RetroReflection') {
if (tableName === 'Organization') {
const rowCountResult = await checkRowCount(tableName)
const rethinkQuery = (updatedAt: Date, id: string | number) => {
return r
.table('RetroReflection' as any)
.table('Organization' as any)
.between([updatedAt, id], [r.maxval, r.maxval], {
index: 'updatedAtId',
leftBound: 'open',
Expand All @@ -50,12 +51,9 @@ const checkRethinkPgEquality: MutationResolvers['checkRethinkPgEquality'] = asyn
}
const pgQuery = async (ids: string[]) => {
return getKysely()
.selectFrom('RetroReflection')
.selectFrom('Organization')
.selectAll()
.select(({fn}) => [
fn('to_json', ['entities']).as('entities'),
fn('to_json', ['reactjis']).as('reactjis')
])
.select(({fn}) => [fn('to_json', ['creditCard']).as('creditCard')])
.where('id', 'in', ids)
.execute()
}
Expand All @@ -64,23 +62,30 @@ const checkRethinkPgEquality: MutationResolvers['checkRethinkPgEquality'] = asyn
pgQuery,
{
id: defaultEqFn,
activeDomain: compareRValUndefinedAsNullAndTruncateRVal(100),
isActiveDomainTouched: compareRValUndefinedAsFalse,
creditCard: compareRValOptionalPluckedObject({
brand: compareRValUndefinedAsNull,
expiry: compareRValUndefinedAsNull,
last4: compareRValStringAsNumber
}),
createdAt: defaultEqFn,
name: compareRValUndefinedAsNullAndTruncateRVal(100),
payLaterClickCount: compareRValUndefinedAsZero,
periodEnd: compareRValUndefinedAsNull,
periodStart: compareRValUndefinedAsNull,
picture: compareRValUndefinedAsNull,
showConversionModal: compareRValUndefinedAsFalse,
stripeId: compareRValUndefinedAsNull,
stripeSubscriptionId: compareRValUndefinedAsNull,
upcomingInvoiceEmailSentAt: compareRValUndefinedAsNull,
tier: defaultEqFn,
tierLimitExceededAt: compareRValUndefinedAsNull,
trialStartDate: compareRValUndefinedAsNull,
scheduledLockAt: compareRValUndefinedAsNull,
lockedAt: compareRValUndefinedAsNull,
updatedAt: compareDateAlmostEqual,
isActive: defaultEqFn,
meetingId: defaultEqFn,
promptId: defaultEqFn,
creatorId: compareRValUndefinedAsNull,
sortOrder: defaultEqFn,
reflectionGroupId: defaultEqFn,
content: compareRValUndefinedAsNullAndTruncateRVal(2000, 0.19),
plaintextContent: compareOptionalPlaintextContent,
entities: compareRValOptionalPluckedArray({
name: defaultEqFn,
salience: compareRealNumber,
lemma: compareRValUndefinedAsNull
}),
reactjis: compareRValUndefinedAsEmptyArray,
sentimentScore: compareRValUndefinedAsNull
featureFlags: compareRValUndefinedAsEmptyArray
},
maxErrors
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import {Kysely, PostgresDialect, sql} from 'kysely'
import {r} from 'rethinkdb-ts'
import connectRethinkDB from '../../database/connectRethinkDB'
import getPg from '../getPg'

const toCreditCard = (creditCard: any) => {
if (!creditCard) return null
return sql<string>`(select json_populate_record(null::"CreditCard", ${JSON.stringify(creditCard)}))`
}

export async function up() {
await connectRethinkDB()
const pg = new Kysely<any>({
dialect: new PostgresDialect({
pool: getPg()
})
})
try {
console.log('Adding index')
await r
.table('Organization')
.indexCreate('updatedAtId', (row: any) => [row('updatedAt'), row('id')])
.run()
await r.table('Organization').indexWait().run()
} catch {
// index already exists
}
console.log('Adding index complete')
const MAX_PG_PARAMS = 65545
const PG_COLS = [
'id',
'activeDomain',
'isActiveDomainTouched',
'creditCard',
'createdAt',
'name',
'payLaterClickCount',
'periodEnd',
'periodStart',
'picture',
'showConversionModal',
'stripeId',
'stripeSubscriptionId',
'upcomingInvoiceEmailSentAt',
'tier',
'tierLimitExceededAt',
'trialStartDate',
'scheduledLockAt',
'lockedAt',
'updatedAt',
'featureFlags'
] as const
type Organization = {
[K in (typeof PG_COLS)[number]]: any
}
const BATCH_SIZE = Math.trunc(MAX_PG_PARAMS / PG_COLS.length)

let curUpdatedAt = r.minval
let curId = r.minval
for (let i = 0; i < 1e6; i++) {
console.log('inserting row', i * BATCH_SIZE, curUpdatedAt, curId)
const rawRowsToInsert = (await r
.table('Organization')
.between([curUpdatedAt, curId], [r.maxval, r.maxval], {
index: 'updatedAtId',
leftBound: 'open',
rightBound: 'closed'
})
.orderBy({index: 'updatedAtId'})
.limit(BATCH_SIZE)
.pluck(...PG_COLS)
.run()) as Organization[]

const rowsToInsert = rawRowsToInsert.map((row) => ({
...row,
activeDomain: row.activeDomain?.slice(0, 100) ?? null,
name: row.name.slice(0, 100),
creditCard: toCreditCard(row.creditCard)
}))
if (rowsToInsert.length === 0) break
const lastRow = rowsToInsert[rowsToInsert.length - 1]
curUpdatedAt = lastRow.updatedAt
curId = lastRow.id
try {
await pg
.insertInto('Organization')
.values(rowsToInsert)
.onConflict((oc) => oc.doNothing())
.execute()
} catch (e) {
await Promise.all(
rowsToInsert.map(async (row) => {
try {
await pg
.insertInto('Organization')
.values(row)
.onConflict((oc) => oc.doNothing())
.execute()
} catch (e) {
console.log(e, row)
}
})
)
}
}
}

export async function down() {
await connectRethinkDB()
try {
await r.table('Organization').indexDrop('updatedAtId').run()
} catch {
// index already dropped
}
const pg = new Kysely<any>({
dialect: new PostgresDialect({
pool: getPg()
})
})
await pg.deleteFrom('Organization').execute()
}
26 changes: 25 additions & 1 deletion packages/server/postgres/utils/rethinkEqualityFns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import stringSimilarity from 'string-similarity'
export const defaultEqFn = (a: unknown, b: unknown) => {
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime()
if (Array.isArray(a) && Array.isArray(b)) return JSON.stringify(a) === JSON.stringify(b)
if (typeof a === 'object' && typeof b === 'object') return JSON.stringify(a) === JSON.stringify(b)
return a === b
}
export const compareDateAlmostEqual = (rVal: unknown, pgVal: unknown) => {
Expand All @@ -30,11 +31,33 @@ export const compareRValUndefinedAsFalse = (rVal: unknown, pgVal: unknown) => {
return normalizedRVal === pgVal
}

export const compareRValUndefinedAsZero = (rVal: unknown, pgVal: unknown) => {
const normalizedRVal = rVal === undefined ? 0 : rVal
return normalizedRVal === pgVal
}

export const compareRValUndefinedAsEmptyArray = (rVal: unknown, pgVal: unknown) => {
const normalizedRVal = rVal === undefined ? [] : rVal
return defaultEqFn(normalizedRVal, pgVal)
}

export const compareRValStringAsNumber = (rVal: unknown, pgVal: unknown) => {
const normalizedRVal = Number(rVal)
return defaultEqFn(normalizedRVal, pgVal)
}

export const compareRValOptionalPluckedObject =
(pluckFields: Record<string, typeof defaultEqFn>) => (rVal: unknown, pgVal: unknown) => {
if (!rVal && !pgVal) return true
const rValObj = rVal || {}
const pgValItem = pgVal || {}
return Object.keys(pluckFields).every((prop) => {
const eqFn = pluckFields[prop]!
const rValItemProp = rValObj[prop as keyof typeof rValObj]
const pgValItemProp = pgValItem[prop as keyof typeof pgValItem]
return eqFn(rValItemProp, pgValItemProp)
})
}
export const compareRValOptionalPluckedArray =
(pluckFields: Record<string, typeof defaultEqFn>) => (rVal: unknown, pgVal: unknown) => {
const rValArray = Array.isArray(rVal) ? rVal : []
Expand All @@ -56,7 +79,8 @@ export const compareRValOptionalPluckedArray =
}

export const compareRValUndefinedAsNullAndTruncateRVal =
(length: number, similarity?: number) => (rVal: unknown, pgVal: unknown) => {
(length: number, similarity = 1) =>
(rVal: unknown, pgVal: unknown) => {
const truncatedRVal = typeof rVal === 'string' ? rVal.slice(0, length) : rVal
const normalizedRVal = truncatedRVal === undefined ? null : truncatedRVal
if (
Expand Down
Loading