Cordova import big files into database using transactions











up vote
5
down vote

favorite












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







New contributor




Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    5
    down vote

    favorite












    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







    New contributor




    Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      5
      down vote

      favorite









      up vote
      5
      down vote

      favorite











      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







      New contributor




      Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      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







      New contributor




      Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Nov 19 at 12:13









      Alexandru D

      262




      262




      New contributor




      Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Alexandru D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          3
          down vote













          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',
            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
            });


            }
            });






            Alexandru D is a new contributor. Be nice, and check out our Code of Conduct.










             

            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








            up vote
            3
            down vote













            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

























              up vote
              3
              down vote













              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























                up vote
                3
                down vote










                up vote
                3
                down vote









                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 at 15:50









                DaveAlden

                19.6k95393




                19.6k95393






















                    Alexandru D is a new contributor. Be nice, and check out our Code of Conduct.










                     

                    draft saved


                    draft discarded


















                    Alexandru D is a new contributor. Be nice, and check out our Code of Conduct.













                    Alexandru D is a new contributor. Be nice, and check out our Code of Conduct.












                    Alexandru D is a new contributor. Be nice, and check out our Code of Conduct.















                     


                    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

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    TypeError: fit_transform() missing 1 required positional argument: 'X'