Cordova import big files into database using transactions












5














I have a txt file of about 17 mb that I have to parse, splitting it line by line and then to add it into the database using transactions.
If the file is too large and I try to open it, the application will run out of memory, so I tried to read it in pieces and then import each piece into the database. Due to the transactions, the data entered in DB is not correct.
There is a part of the used code:



await file_reader.resolveLocalFilesystemUrl(path + file).then(async (file_entry: any) => {

await file_entry.file(async (file) => {

let reader = new FileReader();

reader.onprogress = async (reader_result: any) => {

let loaded = _.cloneDeep(reader_result.loaded);
let total = _.cloneDeep(reader_result.total);
let is_last_element: boolean = _.cloneDeep(loaded == total);
let i: number = 0;
let document_length = this.sync_parser.getReaderLength();
let event_type: number = this.sync_parser.getEventType();

content = iconv.encode(reader.result, encoding).toString();

await this.db.db.transaction(async (database: any) => {
while (document_length >= i) {
if (event_type == SyncParserIo.START_TAG) {
this.table = await this.newHeader(this.sync_parser.getName());
} else if (event_type == SyncParserIo.END_TAG) {
// this.file_content = null;
} else if (event_type == SyncParserIo.ROW) {
// here I execute basic_update_insert function
}
event_type = this.sync_parser.next(i);
i++;
}

}).then(()=>{
this.logger.info(this.TAG, "End document from transaction");
}).catch((e)=>{
//log
});

if (is_last_element) {
resolve(true);
}

};

await reader.readAsBinaryString(file);
});
}).catch((e) => {
this.logger.error("FileSystem Error", e.message);
return reject(e);
});


protected basic_update_insert(table, rows_map, where, where_bindings, database?) {
let db_query = database != null ? database : this.database;
let update_query_util: any = DbUtil.update(table, rows_map, where, where_bindings);
let insert_query_util: any = DbUtil.insert(table, rows_map);

this.import_result = null;

db_query.executeSql(update_query_util.query, update_query_util.bindings, (tx, res) => {

if (res.rowsAffected === 0) {
tx.executeSql(insert_query_util.query, insert_query_util.bindings, (tx2, insert_result) => {
if (insert_result.insertId != null) {
this.import_result = ImporterIo.RESULT_OK;
}
}, (e) => {
this.import_result = ImporterIo.ERROR_INSERT_ROW;
});

} else if (res.rowsAffected === 1) {
this.import_result = ImporterIo.RESULT_OK;
} else if (res.rowsAffected > 1) {
this.import_result = ImporterIo.RESULT_OK;
}

}, (e) => {
this.logger.error(this.TAG, `error from ${table} update`, e);
this.import_result = ImporterIo.ERROR_UPDATE_ROW;
});
}









share|improve this question



























    5














    I have a txt file of about 17 mb that I have to parse, splitting it line by line and then to add it into the database using transactions.
    If the file is too large and I try to open it, the application will run out of memory, so I tried to read it in pieces and then import each piece into the database. Due to the transactions, the data entered in DB is not correct.
    There is a part of the used code:



    await file_reader.resolveLocalFilesystemUrl(path + file).then(async (file_entry: any) => {

    await file_entry.file(async (file) => {

    let reader = new FileReader();

    reader.onprogress = async (reader_result: any) => {

    let loaded = _.cloneDeep(reader_result.loaded);
    let total = _.cloneDeep(reader_result.total);
    let is_last_element: boolean = _.cloneDeep(loaded == total);
    let i: number = 0;
    let document_length = this.sync_parser.getReaderLength();
    let event_type: number = this.sync_parser.getEventType();

    content = iconv.encode(reader.result, encoding).toString();

    await this.db.db.transaction(async (database: any) => {
    while (document_length >= i) {
    if (event_type == SyncParserIo.START_TAG) {
    this.table = await this.newHeader(this.sync_parser.getName());
    } else if (event_type == SyncParserIo.END_TAG) {
    // this.file_content = null;
    } else if (event_type == SyncParserIo.ROW) {
    // here I execute basic_update_insert function
    }
    event_type = this.sync_parser.next(i);
    i++;
    }

    }).then(()=>{
    this.logger.info(this.TAG, "End document from transaction");
    }).catch((e)=>{
    //log
    });

    if (is_last_element) {
    resolve(true);
    }

    };

    await reader.readAsBinaryString(file);
    });
    }).catch((e) => {
    this.logger.error("FileSystem Error", e.message);
    return reject(e);
    });


    protected basic_update_insert(table, rows_map, where, where_bindings, database?) {
    let db_query = database != null ? database : this.database;
    let update_query_util: any = DbUtil.update(table, rows_map, where, where_bindings);
    let insert_query_util: any = DbUtil.insert(table, rows_map);

    this.import_result = null;

    db_query.executeSql(update_query_util.query, update_query_util.bindings, (tx, res) => {

    if (res.rowsAffected === 0) {
    tx.executeSql(insert_query_util.query, insert_query_util.bindings, (tx2, insert_result) => {
    if (insert_result.insertId != null) {
    this.import_result = ImporterIo.RESULT_OK;
    }
    }, (e) => {
    this.import_result = ImporterIo.ERROR_INSERT_ROW;
    });

    } else if (res.rowsAffected === 1) {
    this.import_result = ImporterIo.RESULT_OK;
    } else if (res.rowsAffected > 1) {
    this.import_result = ImporterIo.RESULT_OK;
    }

    }, (e) => {
    this.logger.error(this.TAG, `error from ${table} update`, e);
    this.import_result = ImporterIo.ERROR_UPDATE_ROW;
    });
    }









    share|improve this question

























      5












      5








      5







      I have a txt file of about 17 mb that I have to parse, splitting it line by line and then to add it into the database using transactions.
      If the file is too large and I try to open it, the application will run out of memory, so I tried to read it in pieces and then import each piece into the database. Due to the transactions, the data entered in DB is not correct.
      There is a part of the used code:



      await file_reader.resolveLocalFilesystemUrl(path + file).then(async (file_entry: any) => {

      await file_entry.file(async (file) => {

      let reader = new FileReader();

      reader.onprogress = async (reader_result: any) => {

      let loaded = _.cloneDeep(reader_result.loaded);
      let total = _.cloneDeep(reader_result.total);
      let is_last_element: boolean = _.cloneDeep(loaded == total);
      let i: number = 0;
      let document_length = this.sync_parser.getReaderLength();
      let event_type: number = this.sync_parser.getEventType();

      content = iconv.encode(reader.result, encoding).toString();

      await this.db.db.transaction(async (database: any) => {
      while (document_length >= i) {
      if (event_type == SyncParserIo.START_TAG) {
      this.table = await this.newHeader(this.sync_parser.getName());
      } else if (event_type == SyncParserIo.END_TAG) {
      // this.file_content = null;
      } else if (event_type == SyncParserIo.ROW) {
      // here I execute basic_update_insert function
      }
      event_type = this.sync_parser.next(i);
      i++;
      }

      }).then(()=>{
      this.logger.info(this.TAG, "End document from transaction");
      }).catch((e)=>{
      //log
      });

      if (is_last_element) {
      resolve(true);
      }

      };

      await reader.readAsBinaryString(file);
      });
      }).catch((e) => {
      this.logger.error("FileSystem Error", e.message);
      return reject(e);
      });


      protected basic_update_insert(table, rows_map, where, where_bindings, database?) {
      let db_query = database != null ? database : this.database;
      let update_query_util: any = DbUtil.update(table, rows_map, where, where_bindings);
      let insert_query_util: any = DbUtil.insert(table, rows_map);

      this.import_result = null;

      db_query.executeSql(update_query_util.query, update_query_util.bindings, (tx, res) => {

      if (res.rowsAffected === 0) {
      tx.executeSql(insert_query_util.query, insert_query_util.bindings, (tx2, insert_result) => {
      if (insert_result.insertId != null) {
      this.import_result = ImporterIo.RESULT_OK;
      }
      }, (e) => {
      this.import_result = ImporterIo.ERROR_INSERT_ROW;
      });

      } else if (res.rowsAffected === 1) {
      this.import_result = ImporterIo.RESULT_OK;
      } else if (res.rowsAffected > 1) {
      this.import_result = ImporterIo.RESULT_OK;
      }

      }, (e) => {
      this.logger.error(this.TAG, `error from ${table} update`, e);
      this.import_result = ImporterIo.ERROR_UPDATE_ROW;
      });
      }









      share|improve this question













      I have a txt file of about 17 mb that I have to parse, splitting it line by line and then to add it into the database using transactions.
      If the file is too large and I try to open it, the application will run out of memory, so I tried to read it in pieces and then import each piece into the database. Due to the transactions, the data entered in DB is not correct.
      There is a part of the used code:



      await file_reader.resolveLocalFilesystemUrl(path + file).then(async (file_entry: any) => {

      await file_entry.file(async (file) => {

      let reader = new FileReader();

      reader.onprogress = async (reader_result: any) => {

      let loaded = _.cloneDeep(reader_result.loaded);
      let total = _.cloneDeep(reader_result.total);
      let is_last_element: boolean = _.cloneDeep(loaded == total);
      let i: number = 0;
      let document_length = this.sync_parser.getReaderLength();
      let event_type: number = this.sync_parser.getEventType();

      content = iconv.encode(reader.result, encoding).toString();

      await this.db.db.transaction(async (database: any) => {
      while (document_length >= i) {
      if (event_type == SyncParserIo.START_TAG) {
      this.table = await this.newHeader(this.sync_parser.getName());
      } else if (event_type == SyncParserIo.END_TAG) {
      // this.file_content = null;
      } else if (event_type == SyncParserIo.ROW) {
      // here I execute basic_update_insert function
      }
      event_type = this.sync_parser.next(i);
      i++;
      }

      }).then(()=>{
      this.logger.info(this.TAG, "End document from transaction");
      }).catch((e)=>{
      //log
      });

      if (is_last_element) {
      resolve(true);
      }

      };

      await reader.readAsBinaryString(file);
      });
      }).catch((e) => {
      this.logger.error("FileSystem Error", e.message);
      return reject(e);
      });


      protected basic_update_insert(table, rows_map, where, where_bindings, database?) {
      let db_query = database != null ? database : this.database;
      let update_query_util: any = DbUtil.update(table, rows_map, where, where_bindings);
      let insert_query_util: any = DbUtil.insert(table, rows_map);

      this.import_result = null;

      db_query.executeSql(update_query_util.query, update_query_util.bindings, (tx, res) => {

      if (res.rowsAffected === 0) {
      tx.executeSql(insert_query_util.query, insert_query_util.bindings, (tx2, insert_result) => {
      if (insert_result.insertId != null) {
      this.import_result = ImporterIo.RESULT_OK;
      }
      }, (e) => {
      this.import_result = ImporterIo.ERROR_INSERT_ROW;
      });

      } else if (res.rowsAffected === 1) {
      this.import_result = ImporterIo.RESULT_OK;
      } else if (res.rowsAffected > 1) {
      this.import_result = ImporterIo.RESULT_OK;
      }

      }, (e) => {
      this.logger.error(this.TAG, `error from ${table} update`, e);
      this.import_result = ImporterIo.ERROR_UPDATE_ROW;
      });
      }






      sql typescript cordova ionic-framework transactions






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 '18 at 12:13









      Alexandru D

      262




      262
























          1 Answer
          1






          active

          oldest

          votes


















          3














          You may find cordova-sqlite-porter to be useful (there is an Ionic Native Typescript wrapper).
          It wraps the SQLite DB API, allowing you to pass it a data dump formatted either as SQL statements or as JSON.



          With such a large amount of data, it may be in your interests to convert the data to the JSON structure supported by the plugin since it translates the JSON into batched inserts which, in the plugin example project, leads to an observable performance improvement when importing data of 100 times faster.



          Alternatively, you may wish to rework your SQL INSERT statements manually to make use of the UNION SELECT optimisation as outlined in this answer.






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53374415%2fcordova-import-big-files-into-database-using-transactions%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            You may find cordova-sqlite-porter to be useful (there is an Ionic Native Typescript wrapper).
            It wraps the SQLite DB API, allowing you to pass it a data dump formatted either as SQL statements or as JSON.



            With such a large amount of data, it may be in your interests to convert the data to the JSON structure supported by the plugin since it translates the JSON into batched inserts which, in the plugin example project, leads to an observable performance improvement when importing data of 100 times faster.



            Alternatively, you may wish to rework your SQL INSERT statements manually to make use of the UNION SELECT optimisation as outlined in this answer.






            share|improve this answer


























              3














              You may find cordova-sqlite-porter to be useful (there is an Ionic Native Typescript wrapper).
              It wraps the SQLite DB API, allowing you to pass it a data dump formatted either as SQL statements or as JSON.



              With such a large amount of data, it may be in your interests to convert the data to the JSON structure supported by the plugin since it translates the JSON into batched inserts which, in the plugin example project, leads to an observable performance improvement when importing data of 100 times faster.



              Alternatively, you may wish to rework your SQL INSERT statements manually to make use of the UNION SELECT optimisation as outlined in this answer.






              share|improve this answer
























                3












                3








                3






                You may find cordova-sqlite-porter to be useful (there is an Ionic Native Typescript wrapper).
                It wraps the SQLite DB API, allowing you to pass it a data dump formatted either as SQL statements or as JSON.



                With such a large amount of data, it may be in your interests to convert the data to the JSON structure supported by the plugin since it translates the JSON into batched inserts which, in the plugin example project, leads to an observable performance improvement when importing data of 100 times faster.



                Alternatively, you may wish to rework your SQL INSERT statements manually to make use of the UNION SELECT optimisation as outlined in this answer.






                share|improve this answer












                You may find cordova-sqlite-porter to be useful (there is an Ionic Native Typescript wrapper).
                It wraps the SQLite DB API, allowing you to pass it a data dump formatted either as SQL statements or as JSON.



                With such a large amount of data, it may be in your interests to convert the data to the JSON structure supported by the plugin since it translates the JSON into batched inserts which, in the plugin example project, leads to an observable performance improvement when importing data of 100 times faster.



                Alternatively, you may wish to rework your SQL INSERT statements manually to make use of the UNION SELECT optimisation as outlined in this answer.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 19 '18 at 15:50









                DaveAlden

                20k95394




                20k95394






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53374415%2fcordova-import-big-files-into-database-using-transactions%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith