Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Created October 11, 2014 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nolanlawson/9b5c13afb1ac0f7e70fe to your computer and use it in GitHub Desktop.
Save nolanlawson/9b5c13afb1ac0f7e70fe to your computer and use it in GitHub Desktop.
Test \u0000 string truncation in Web SQL
<html>
<body>
<h1>Test \u0000 string truncation in Web SQL</h1>
<p>Details <a href='https://github.com/pouchdb/pouchdb/pull/1731#issuecomment-38622342'>in this PouchDB bug</a>.</p>
<pre id="display"></pre>
<script src="index.js"></script>
</body>
</html>
(function() {
'use strict';
var display = document.getElementById('display');
function log(str) {
display.innerHTML += '\n' + str;
}
function decodeUtf8(str) {
return decodeURIComponent(window.escape(str));
}
function parseHexString(str, encoding) {
var result = '';
var charWidth = encoding === 'UTF-8' ? 2 : 4;
for (var i = 0, len = str.length; i < len; i += charWidth) {
var substring = str.substring(i, i + charWidth);
if (charWidth === 4) { // UTF-16, twiddle the bits
substring = substring.substring(2, 4) + substring.substring(0, 2);
}
result += String.fromCharCode(parseInt(substring, 16));
}
result = encoding === 'UTF-8' ? decodeUtf8(result) : result;
return result;
}
var db = openDatabase('Demo', "1.0", "Demo", 5000000);
db.transaction(function (tx) {
var sql = 'SELECT ? AS mystring';
var sqlArgs = ['foo\u0000bar'];
log('executing "' + sql + '" with args ' + JSON.stringify(sqlArgs));
tx.executeSql(sql, sqlArgs, function (tx, res) {
var mystring = res.rows.item(0).mystring;
log("string returned: " + JSON.stringify(mystring));
log("if the bug is present, then it will be cut off after \\u0000");
log('\nokay, let\'s try hex() instead');
sql = 'SELECT hex(?) AS hex';
sqlArgs = ['foo\u0000bar'];
log('executing "' + sql + '" with args ' + JSON.stringify(sqlArgs));
tx.executeSql(sql, sqlArgs, function (tx, res) {
var hex = res.rows.item(0).hex;
log("string returned: " + JSON.stringify(hex));
log("\nlet's parse that hex...");
// can determine the DB's encoding based on the length of
// the hex returned. pre-7.1 Safari is UTF-16.
var encoding = hex.length === 14 ? 'UTF-8' : 'UTF-16';
var parsed = parseHexString(hex, encoding);
log('parsed string is: ' + JSON.stringify(parsed));
log("that's funny, the whole string is there now!");
});
});
}, function(err) {
log('unexpected error: ' + err.message);
}, function () {
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment