Skip to content

Commit efa6e63

Browse files
committed
💪 Improve database import logic
1 parent 62d33f1 commit efa6e63

File tree

2 files changed

+39
-12
lines changed

2 files changed

+39
-12
lines changed

‎lib/class/document.js‎

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -914,30 +914,57 @@ Document.setMethod(function exportToStream(output) {
914914
*
915915
* @return {Pledge}
916916
*/
917-
Document.setMethod(function importFromBuffer(buffer) {
917+
Document.setMethod(function importFromBuffer(buffer, options) {
918918

919919
var that = this,
920920
pledge = new Pledge();
921921

922+
if (!options) {
923+
options = {};
924+
}
925+
922926
zlib.gunzip(buffer, async function unzipped(err, data) {
923927

924928
if (err) {
925929
return pledge.reject(err);
926930
}
927931

928-
data = JSON.undry(data.toString());
932+
try {
933+
data = JSON.undry(data.toString());
929934

930-
that.$main = data;
935+
that.$main = data;
931936

932-
await that.save(null, {
933-
validate : false,
934-
override_created : true,
935-
set_updated : false,
936-
importing : true,
937-
create : true, // Force INSERT since we're importing
938-
});
937+
let save_options = {
938+
validate : false,
939+
override_created : true,
940+
set_updated : false,
941+
importing : true,
942+
};
939943

940-
pledge.resolve();
944+
// If replace_existing is true, don't force create (allow update)
945+
// Otherwise, force INSERT
946+
if (!options.replace_existing) {
947+
save_options.create = true;
948+
}
949+
950+
await that.save(null, save_options);
951+
952+
pledge.resolve();
953+
} catch (save_err) {
954+
// Ensure we have a proper Error object with a message
955+
let error = save_err;
956+
957+
if (!error) {
958+
error = new Error('Unknown error during document import');
959+
} else if (!(error instanceof Error)) {
960+
// If it's not an Error object, wrap it
961+
let message = error.message || error.errmsg || String(error);
962+
error = new Error('Import save failed: ' + message);
963+
error.originalError = save_err;
964+
}
965+
966+
pledge.reject(error);
967+
}
941968
});
942969

943970
return pledge;

‎lib/class/import_stream_parser.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ ImportStreamParser.setMethod(function handlePayload() {
261261
this.paused = true;
262262
this.pending_import = true;
263263

264-
this.doc.importFromBuffer(this.value).done(function done(err, result) {
264+
this.doc.importFromBuffer(this.value, this.options).done(function done(err, result) {
265265

266266
that.pending_import = false;
267267

0 commit comments

Comments
 (0)