5

I have an array

newData = [{ sId: 'XXXXXX', itemlName: 'LSストレッ', iCode: 'XXXXXX', iType: '', skus: 'XXXXXXX', iLevel: 'L2', cCode: '88', cName: 'Other', sCode: '999', sName: 'No Control', pLengthCode: '988', core: 'N', sCode: '1', dCode: 'XX', gDeptCode: 'XX', gDeptName: 'Women\\\'s Items', rCode: 'jqs' },{ sId: 'XXXXXX', itemlName: 'LSストレッ', iCode: 'XXXXXX', iType: '', skus: 'XXXXXXX', iLevel: 'L2', cCode: '88', cName: 'Other', sCode: '999', sName: 'No Control', pLengthCode: '988', core: 'N', sCode: '1', dCode: 'XX', gDeptCode: 'XX', gDeptName: 'Women\\\'s Items', rCode: 'jqs' }]

I wants to insert newData in to mysql database using objection.js. But when I run my node application , I got the error saying:

Error: batch insert only works with Postgresql

My insert code is -:

samplemodel.query().insert( newData );

How can I perform the batch insertion of array data in mysql data base using objection.js?

CinCout
  • 9,486
  • 12
  • 49
  • 67
Johncy Binoy
  • 169
  • 3
  • 13

5 Answers5

8

Error: batch insert only works with Postgresql

Well, that means that you need Postgres's instead of Mysql to make it work.

Edit1:

From the docs:

If you are using Postgres the inserts are done in batches for maximum performance. On other databases the rows need to be inserted one at a time. This is because postgresql is the only database engine that returns the identifiers of all inserted rows and not just the first or the last one.

That means that if you are using mysql you should do

samplemodel.query().insert(data);

For each element in the "newData" array.

19greg96
  • 2,592
  • 5
  • 41
  • 55
Borjante
  • 9,767
  • 6
  • 35
  • 61
7

You can call

samplemodel.query().insertWithRelated( newData );

which uses multiple queries if needed and works with all databases.

Sami Koskimäki
  • 250
  • 2
  • 7
4

In latest version of Objection insertWithRelated Deprecated!

Instead you need to use insertGraph

samplemodel.query().insertGraph(newData);

or

samplemodel.query().insertGraph(newData, { allowRefs: true });
Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
3

Hence there is no way to reduce number of queries, due to mysql limitations.

I would loop over it insert it into array of promises and execute it throw Promise.all

...
let insertPromises = []
for(let item of newData){
    insertPromises.push(samplemode.query().insert(item))
}

Promise.all(insertPromises).then(() => { ... })
...

I would suggest using transactions if I'm using this approach with $query or $relatedQuery to ensure data integerity

Ahmed Gaber
  • 188
  • 2
  • 5
1

The trick is to make the convert the insert statement into a string and execute the raw sql.

Something like

let insertQuery = samplemodel.query().insert( newData ); let insertRes = await knex.raw(insertQuery.toString())

PS: if this is not good practice, I'd appreciate you letting me know!

user3662456
  • 267
  • 2
  • 11