@@ -54,6 +54,10 @@ export async function moveFromMongoToPG (
5454 client . close ( )
5555}
5656
57+ function escapeBackticks ( str : string ) : string {
58+ return str . replaceAll ( "'" , "''" )
59+ }
60+
5761async function moveWorkspace (
5862 accountDb : AccountDB ,
5963 mongo : MongoClient ,
@@ -77,32 +81,38 @@ async function moveWorkspace (
7781 for ( const collection of collections ) {
7882 const cursor = collection . find ( )
7983 const domain = translateDomain ( collection . collectionName )
84+ const current = await pgClient . query ( `SELECT _id FROM ${ domain } WHERE "workspaceId" = $1` , [ ws . workspace ] )
85+ const currentIds = new Set ( current . rows . map ( ( r ) => r . _id ) )
8086 console . log ( 'move domain' , domain )
87+ const docs : Doc [ ] = [ ]
8188 while ( true ) {
82- const doc = ( await cursor . next ( ) ) as Doc | null
83- if ( doc === null ) break
84- try {
85- const converted = convertDoc ( doc , ws . workspaceName ?? ws . workspace )
86- await retryTxn ( pgClient , async ( client ) => {
87- await client . query (
88- `INSERT INTO ${ domain } (_id, "workspaceId", _class, "createdBy", "modifiedBy", "modifiedOn", "createdOn", space, "attachedTo", data) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)` ,
89- [
90- converted . _id ,
91- converted . workspaceId ,
92- converted . _class ,
93- converted . createdBy ?? converted . modifiedBy ,
94- converted . modifiedBy ,
95- converted . modifiedOn ,
96- converted . createdOn ?? converted . modifiedOn ,
97- converted . space ,
98- converted . attachedTo ,
99- converted . data
100- ]
101- )
102- } )
103- } catch ( err ) {
104- console . log ( 'error when move doc' , doc . _id , doc . _class , err )
105- continue
89+ while ( docs . length < 50000 ) {
90+ const doc = ( await cursor . next ( ) ) as Doc | null
91+ if ( doc === null ) break
92+ if ( currentIds . has ( doc . _id ) ) continue
93+ docs . push ( doc )
94+ }
95+ if ( docs . length === 0 ) break
96+ while ( docs . length > 0 ) {
97+ const part = docs . splice ( 0 , 500 )
98+ const vals = part
99+ . map ( ( doc ) => {
100+ const d = convertDoc ( doc , ws . workspace )
101+ return `('${ d . _id } ', '${ d . workspaceId } ', '${ d . _class } ', '${ d . createdBy ?? d . modifiedBy } ', '${ d . modifiedBy } ', ${ d . modifiedOn } , ${ d . createdOn ?? d . modifiedOn } , '${ d . space } ', ${
102+ d . attachedTo != null ? `'${ d . attachedTo } '` : 'NULL'
103+ } , '${ escapeBackticks ( JSON . stringify ( d . data ) ) } ')`
104+ } )
105+ . join ( ', ' )
106+ try {
107+ await retryTxn ( pgClient , async ( client ) => {
108+ await client . query (
109+ `INSERT INTO ${ translateDomain ( domain ) } (_id, "workspaceId", _class, "createdBy", "modifiedBy", "modifiedOn", "createdOn", space, "attachedTo", data) VALUES ${ vals } `
110+ )
111+ } )
112+ } catch ( err ) {
113+ console . log ( 'error when move doc to' , domain , err )
114+ continue
115+ }
106116 }
107117 }
108118 }
0 commit comments