question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Inserting in a loop does not insert all keys.

See original GitHub issue

I was troubleshooting an issue with a wrapper I made, and finally realized this seems to be a native level issue. When inserting 100,000 records in a level database, some keys are missing. Exactly 433 to be precise.

Here is my test code

const Level = require('level');
const db = new Level('./data/points');
const test = new Map();

(async function() {
  console.time('100000 Inserts');
  for (let i = 0; i < 100000; i++) {
    await db.put(`test${i}`, 'simple string');
  }
  console.timeEnd('100000 Inserts');
  await fetchEverything();
  console.log(`${test.size} keys loaded.`);
  for(let i = 0; i < 100000; i++) {
    if(!test.has(`test${i}`))
      console.log(`Missing test${i}`);
  }
}());

const fetchEverything = async function() {
  return new Promise((resolve) => {
    const stream = db.keyStream();
    stream.on('data', (key) => {
      db.get(key, (err, value) => {
        if (err) {
          console.error(`Error loading: ${err}`);
        }
        test.set(key, value);
      });
    });
    stream.on('end', () =>
      resolve()
    );
  });
}

Every time I run this, it says it inserts 100000, but when I fetch everything… I only get 99567 keys loaded. The strangest thing is, all those keys start with test9, such as test9, test99, test999. I have tried this multiple times, and always get the exact same number of keys, never more or less.

I’m on level 3.0.0, running under Windows 10 (Fully updated to Creators and all further patches). No errors are logged when fetching the values. Issue also happens on Ubuntu Server 16.04. Node versions are 8.10 and 9.9 respectively.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
eslachancecommented, Apr 2, 2018

Ah, I see what’s happening. I did not realize that the stream end event happened before all get promises were resolved. I would assume using Promise.all(fetches).then(()=> resolve()) would work, assuming fetches is an array of all the db.get() promises. Thanks for the information, guys!

1reaction
juliangrubercommented, Apr 2, 2018

@ralphtheninja’s observations are correct, just adding another alternative:

const {promisify} = require('util')
const read = promisify(require('stream-read'))

const fetchEverything = async () => {
  const stream = db.createReadStream()
  let key, value
  for (({ key, value }) = await read(stream)) test.set(key, value)
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Mysql query within for loop not inserting all values
First of all insert all data using one query. Generate it in for loop and call mysql query once. You can check if...
Read more >
Inserting elements in std::map (insert, emplace and operator [])
The insertion only takes place when the key passed is not already inset. It returns a pointer pair. First element points to the...
Read more >
5. Data Structures — Python 3.11.1 documentation
It is an error to extract a value using a non-existent key. Performing list(d) on a dictionary returns a list of all the...
Read more >
Performance issue with Insert ACCEPTING DUPLICATE KEYS.
This insert is not in between loop / end loop. This is the code . INSERT ztable FROM TABLE it_links ACCEPTING DUPLICATE KEYS....
Read more >
Understanding While loops in SQL Server - SQLShack
Inserting records with SQL While loop. Let's now see how the SQL While loop is used to insert dummy records in a database...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found