├── .gitattributes ├── .stylelintrc.json ├── index.js ├── .gitignore ├── .npmignore ├── .editorconfig ├── inch.json ├── docs ├── CHANGELOG.md └── api.md ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── workflows │ └── ci.yml └── CONTRIBUTING.md ├── .eslintrc.js ├── .jsbeautifyrc ├── package.json ├── README.md ├── lib └── upsert.js ├── test └── spec │ ├── integration-spec.js │ └── upsert-spec.js └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | * text eol=lf 2 | -------------------------------------------------------------------------------- /.stylelintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "stylelint-config-standard" 3 | } 4 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = require('./lib/upsert'); 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .temp 3 | node_modules 4 | bower_components 5 | npm-debug.log 6 | package-lock.json 7 | .nyc_output 8 | coverage 9 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | target 2 | .temp 3 | .nyc_output 4 | .config 5 | coverage 6 | bower_components 7 | .github 8 | test 9 | example 10 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | indent_style = space 10 | indent_size = 4 11 | 12 | [*.json] 13 | indent_size = 2 14 | -------------------------------------------------------------------------------- /inch.json: -------------------------------------------------------------------------------- 1 | { 2 | "files": { 3 | "included": [ 4 | "*.js", 5 | "lib/**/*.js", 6 | "tasks/**/*.js" 7 | ], 8 | "excluded": [ 9 | "**/Gruntfile.js", 10 | "**/.eslintrc.js", 11 | "**/stylelint.config.js" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /docs/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | | Date | Version | Description | 2 | | ----------- | ------- | ----------- | 3 | | 2020-05-13 | v2.0.0 | Migrate to github actions and upgrade minimal node version | 4 | | 2019-02-08 | v1.2.1 | Maintenance | 5 | | 2016-08-05 | v0.0.43 | Added promise support | 6 | | 2016-03-04 | v0.0.1 | Initial release. | 7 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: sagiegurari 7 | 8 | --- 9 | 10 | ### Feature Description 11 | 12 | 13 | ### Describe The Solution You'd Like 14 | 15 | 16 | ### Code Sample 17 | 18 | ```js 19 | // paste code here 20 | ``` 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: sagiegurari 7 | 8 | --- 9 | 10 | ### Describe The Bug 11 | 12 | 13 | ### To Reproduce 14 | 15 | 16 | ### Error Stack 17 | 18 | ```console 19 | The error stack trace 20 | ``` 21 | 22 | ### Code Sample 23 | 24 | ```js 25 | // paste code here 26 | ``` 27 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'env': { 3 | 'node': true, 4 | 'commonjs': true, 5 | 'es2021': true, 6 | 'mocha': true 7 | }, 8 | 'extends': 'eslint:recommended', 9 | 'parserOptions': { 10 | 'ecmaVersion': 13 11 | }, 12 | 'rules': { 13 | 'indent': [ 14 | 'error', 15 | 4 16 | ], 17 | 'linebreak-style': [ 18 | 'error', 19 | 'unix' 20 | ], 21 | 'quotes': [ 22 | 'error', 23 | 'single' 24 | ], 25 | 'semi': [ 26 | 'error', 27 | 'always' 28 | ] 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | env: 4 | CLICOLOR_FORCE: 1 5 | jobs: 6 | ci: 7 | name: CI 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: ['18.x'] 13 | steps: 14 | - name: Checkout 15 | uses: actions/checkout@v2 16 | - name: Install node.js 17 | uses: actions/setup-node@v1 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - name: Install Dependencies 21 | run: npm install && npm install --no-save simple-oracledb 22 | - name: Run CI 23 | run: npm test 24 | - name: Coveralls 25 | uses: coverallsapp/github-action@master 26 | with: 27 | github-token: ${{ secrets.GITHUB_TOKEN }} 28 | path-to-lcov: './coverage/lcov.info' 29 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | 4 | ## Issues 5 | 6 | Found a bug? Got a question? Want some enhancement?
7 | First place to go is the repository issues section, and I'll try to help as much as possible. 8 | 9 | ## Pull Requests 10 | 11 | Fixed a bug or just want to provided additional functionality?
12 | Simply fork this repository, implement your changes and create a pull request.
13 | Few guidelines regarding pull requests: 14 | 15 | * This repository is integrated with github actions for continuous integration.
16 | 17 | Your pull request build must pass (the build will run automatically).
18 | You can run the following command locally to ensure the build will pass: 19 | 20 | ````sh 21 | npm test 22 | ```` 23 | 24 | * This library is using multiple code inspection tools to validate certain level of standards.
The configuration is part of the repository and you can set your favorite IDE using that configuration.
You can run the following command locally to ensure the code inspection passes: 25 | 26 | ````sh 27 | npm run lint 28 | ```` 29 | 30 | * There are many automatic unit tests as part of the library which provide full coverage of the functionality.
Any fix/enhancement must come with a set of tests to ensure it's working well. 31 | -------------------------------------------------------------------------------- /.jsbeautifyrc: -------------------------------------------------------------------------------- 1 | { 2 | "js": { 3 | "indent_size": 4, 4 | "indent_char": " ", 5 | "eol": "\n", 6 | "indent_level": 0, 7 | "indent_with_tabs": false, 8 | "preserve_newlines": true, 9 | "max_preserve_newlines": 2, 10 | "space_in_paren": false, 11 | "jslint_happy": true, 12 | "space_after_anon_function": true, 13 | "brace_style": "collapse", 14 | "break_chained_methods": false, 15 | "keep_array_indentation": true, 16 | "unescape_strings": false, 17 | "wrap_line_length": 0, 18 | "end_with_newline": true, 19 | "comma_first": false, 20 | "eval_code": false, 21 | "keep_function_indentation": false, 22 | "space_before_conditional": true, 23 | "good_stuff": true 24 | }, 25 | "css": { 26 | "indent_size": 2, 27 | "indent_char": " ", 28 | "indent_with_tabs": false, 29 | "eol": "\n", 30 | "end_with_newline": true, 31 | "selector_separator_newline": false, 32 | "newline_between_rules": true 33 | }, 34 | "html": { 35 | "indent_size": 4, 36 | "indent_char": " ", 37 | "indent_with_tabs": false, 38 | "eol": "\n", 39 | "end_with_newline": true, 40 | "preserve_newlines": true, 41 | "max_preserve_newlines": 2, 42 | "indent_inner_html": true, 43 | "brace_style": "collapse", 44 | "indent_scripts": "normal", 45 | "wrap_line_length": 0, 46 | "wrap_attributes": "auto", 47 | "wrap_attributes_indent_size": 4 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "oracledb-upsert", 3 | "version": "2.0.0", 4 | "description": "UPSERT (insert/update) extension to oracledb.", 5 | "author": { 6 | "name": "Sagie Gur-Ari", 7 | "email": "sagiegurari@gmail.com" 8 | }, 9 | "license": "Apache-2.0", 10 | "homepage": "http://github.com/sagiegurari/oracledb-upsert", 11 | "repository": { 12 | "type": "git", 13 | "url": "http://github.com/sagiegurari/oracledb-upsert.git" 14 | }, 15 | "bugs": { 16 | "url": "http://github.com/sagiegurari/oracledb-upsert/issues" 17 | }, 18 | "keywords": [ 19 | "oracle", 20 | "oracledb", 21 | "database", 22 | "upsert" 23 | ], 24 | "main": "index.js", 25 | "directories": { 26 | "lib": "lib", 27 | "test": "test/spec" 28 | }, 29 | "scripts": { 30 | "clean": "rm -Rf ./.nyc_output ./coverage", 31 | "format": "js-beautify --config ./.jsbeautifyrc --file ./*.js ./lib/**/*.js ./test/**/*.js", 32 | "lint-js": "eslint ./*.js ./lib/**/*.js ./test/**/*.js", 33 | "lint-css": "stylelint --allow-empty-input ./docs/**/*.css", 34 | "lint": "npm run lint-js && npm run lint-css", 35 | "jstest": "mocha --exit ./test/spec/**/*.js", 36 | "coverage": "nyc --reporter=html --reporter=text --reporter=lcovonly --check-coverage=true mocha --exit ./test/spec/**/*.js", 37 | "docs": "jsdoc2md lib/**/*.js > ./docs/api.md", 38 | "test": "npm run clean && npm run format && npm run lint && npm run docs && npm run coverage", 39 | "postpublish": "git fetch && git pull" 40 | }, 41 | "peerDependencies": { 42 | "simple-oracledb": "^2" 43 | }, 44 | "dependencies": {}, 45 | "devDependencies": { 46 | "chai": "^4", 47 | "eslint": "^8", 48 | "js-beautify": "^1", 49 | "jsdoc-to-markdown": "^8", 50 | "mocha": "^10", 51 | "nyc": "^15", 52 | "promiscuous": "^0.7", 53 | "stylelint": "^13", 54 | "stylelint-config-standard": "^22" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /docs/api.md: -------------------------------------------------------------------------------- 1 | ## Classes 2 | 3 |
4 |
Connection
5 |
6 |
7 | 8 | ## Typedefs 9 | 10 |
11 |
AsyncCallback : function
12 |

Invoked when an async operation has finished.

13 |
14 |
15 | 16 | 17 | 18 | ## Connection 19 | **Kind**: global class 20 | **Access**: public 21 | **Author**: Sagie Gur-Ari 22 | 23 | * [Connection](#Connection) 24 | * [new Connection()](#new_Connection_new) 25 | * [.upsert(sqls, bindParams, [options], [callback])](#Connection.upsert) ⇒ Promise 26 | 27 | 28 | 29 | ### new Connection() 30 | This class holds all the extended capabilities added the oracledb connection. 31 | 32 | 33 | 34 | ### Connection.upsert(sqls, bindParams, [options], [callback]) ⇒ Promise 35 | The UPSERT oracledb extension gets 3 SQL statements.
36 | It first queries the database for existing data, based on the output, it either runs INSERT or UPDATE SQL.
37 | If it runs the INSERT and it fails on unique constraint, it will also run the UPDATE.
38 | The output in the callback is the output of the INSERT/UPDATE operation. 39 | 40 | **Kind**: static method of [Connection](#Connection) 41 | **Returns**: Promise - In case of no callback provided in input and promise is supported, this function will return a promise 42 | **Access**: public 43 | 44 | | Param | Type | Description | 45 | | --- | --- | --- | 46 | | sqls | Object | Holds all required SQLs to support the UPSERT capability | 47 | | sqls.query | String | The SELECT SQL statement | 48 | | sqls.insert | String | The INSERT SQL statement | 49 | | sqls.update | String | The UPDATE SQL statement | 50 | | bindParams | Object | The bind parameters used to specify the values for the columns, used by all execute operations (arrays not supported, only named bind params) | 51 | | [options] | Object | Used by all execute operations | 52 | | [callback] | [AsyncCallback](#AsyncCallback) | Invoked once the UPSERT is done with either an error or the output | 53 | 54 | **Example** 55 | ```js 56 | connection.upsert({ 57 | query: 'SELECT ID FROM MY_DATA WHERE ID = :id', 58 | insert: 'INSERT INTO MY_DATA (ID, NAME) VALUES (:id, :name)', 59 | update: 'UPDATE MY_DATA SET NAME = :name WHERE ID = :id' 60 | }, { 61 | id: 110, 62 | name: 'new name' 63 | }, { 64 | autoCommit: false 65 | }, function onUpsert(error, results) { 66 | if (error) { 67 | //handle error... 68 | } else { 69 | console.log('rows affected: ', results.rowsAffected); 70 | 71 | //continue flow... 72 | } 73 | }); 74 | ``` 75 | 76 | 77 | ## AsyncCallback : function 78 | Invoked when an async operation has finished. 79 | 80 | **Kind**: global typedef 81 | 82 | | Param | Type | Description | 83 | | --- | --- | --- | 84 | | [error] | Error | Any possible error | 85 | | [output] | Object | The operation output | 86 | 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # oracledb-upsert 2 | 3 | [![NPM Version](http://img.shields.io/npm/v/oracledb-upsert.svg?style=flat)](https://www.npmjs.org/package/oracledb-upsert) [![CI](https://github.com/sagiegurari/oracledb-upsert/workflows/CI/badge.svg?branch=master)](https://github.com/sagiegurari/oracledb-upsert/actions) [![Coverage Status](https://coveralls.io/repos/sagiegurari/oracledb-upsert/badge.svg)](https://coveralls.io/r/sagiegurari/oracledb-upsert) [![Known Vulnerabilities](https://snyk.io/test/github/sagiegurari/oracledb-upsert/badge.svg)](https://snyk.io/test/github/sagiegurari/oracledb-upsert) [![Inline docs](http://inch-ci.org/github/sagiegurari/oracledb-upsert.svg?branch=master)](http://inch-ci.org/github/sagiegurari/oracledb-upsert) [![License](https://img.shields.io/npm/l/oracledb-upsert.svg?style=flat)](https://github.com/sagiegurari/oracledb-upsert/blob/master/LICENSE) [![Total Downloads](https://img.shields.io/npm/dt/oracledb-upsert.svg?style=flat)](https://www.npmjs.org/package/oracledb-upsert) 4 | 5 | > UPSERT (insert/update) extension to oracledb. 6 | 7 | * [Overview](#overview) 8 | * [Usage](#usage) 9 | * [Installation](#installation) 10 | * [API Documentation](docs/api.md) 11 | * [Contributing](.github/CONTRIBUTING.md) 12 | * [Release History](#history) 13 | * [License](#license) 14 | 15 | 16 | ## Overview 17 | This library extends the oracledb connection object with a new upsert function to enable to run UPDATE or INSERT based on the 18 | data currently in the DB. 19 | 20 | 21 | ## Usage 22 | In order to use this library, you need to extend the main oracledb object as follows: 23 | 24 | ```js 25 | //load the oracledb library 26 | var oracledb = require('oracledb'); 27 | 28 | //load the simple oracledb 29 | var SimpleOracleDB = require('simple-oracledb'); 30 | 31 | //modify the original oracledb library 32 | SimpleOracleDB.extend(oracledb); 33 | 34 | //load the extension 35 | require('oracledb-upsert'); 36 | 37 | //from this point connections fetched via oracledb.getConnection(...) or pool.getConnection(...) 38 | //have access to the UPSERT function. 39 | oracledb.getConnection(function onConnection(error, connection) { 40 | if (error) { 41 | //handle error 42 | } else { 43 | //work with new capabilities or original oracledb capabilities 44 | connection.upsert({ 45 | query: 'SELECT ID FROM MY_DATA WHERE ID = :id', 46 | insert: 'INSERT INTO MY_DATA (ID, NAME) VALUES (:id, :name)', 47 | update: 'UPDATE MY_DATA SET NAME = :name WHERE ID = :id' 48 | }, { 49 | id: 110, 50 | name: 'new name' 51 | }, { 52 | autoCommit: false 53 | }, function onUpsert(error, results) { 54 | if (error) { 55 | //handle error... 56 | } else { 57 | console.log('rows affected: ', results.rowsAffected); 58 | 59 | //continue flow... 60 | } 61 | }); 62 | } 63 | }); 64 | ``` 65 | 66 | 67 | 68 | ### 'connection.upsert(sqls, bindParams, [options], [callback]) ⇒ [Promise]' 69 | The UPSERT oracledb extension gets 3 SQL statements.
70 | It first queries the database for existing data, based on the output, it either runs INSERT or UPDATE SQL.
71 | If it runs the INSERT and it fails on unique constraint, it will also run the UPDATE.
72 | The output in the callback is the output of the INSERT/UPDATE operation. 73 | 74 | **Example** 75 | ```js 76 | connection.upsert({ 77 | query: 'SELECT ID FROM MY_DATA WHERE ID = :id', 78 | insert: 'INSERT INTO MY_DATA (ID, NAME) VALUES (:id, :name)', 79 | update: 'UPDATE MY_DATA SET NAME = :name WHERE ID = :id' 80 | }, { 81 | id: 110, 82 | name: 'new name' 83 | }, { 84 | autoCommit: false 85 | }, function onUpsert(error, results) { 86 | if (error) { 87 | //handle error... 88 | } else { 89 | console.log('rows affected: ', results.rowsAffected); 90 | 91 | //continue flow... 92 | } 93 | }); 94 | ``` 95 | 96 | 97 | 98 | ## Installation 99 | In order to use this library, just run the following npm install command: 100 | 101 | ```sh 102 | npm install --save oracledb-upsert 103 | ``` 104 | 105 | This library doesn't define oracledb as a dependency and therefore it is not installed when installing oracledb-upsert.
106 | You should define oracledb in your package.json and install it based on the oracledb installation instructions found at: [installation guide](https://github.com/oracle/node-oracledb/blob/master/INSTALL.md) 107 | 108 | ## API Documentation 109 | See full docs at: [API Docs](docs/api.md) 110 | 111 | ## Contributing 112 | See [contributing guide](.github/CONTRIBUTING.md) 113 | 114 | 115 | ## Release History 116 | 117 | | Date | Version | Description | 118 | | ----------- | ------- | ----------- | 119 | | 2020-05-13 | v2.0.0 | Migrate to github actions and upgrade minimal node version | 120 | | 2019-02-08 | v1.2.1 | Maintenance | 121 | | 2016-08-05 | v0.0.43 | Added promise support | 122 | | 2016-03-04 | v0.0.1 | Initial release. | 123 | 124 | 125 | ## License 126 | Developed by Sagie Gur-Ari and licensed under the Apache 2 open source license. 127 | -------------------------------------------------------------------------------- /lib/upsert.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Invoked when an async operation has finished. 5 | * 6 | * @callback AsyncCallback 7 | * @param {Error} [error] - Any possible error 8 | * @param {Object} [output] - The operation output 9 | */ 10 | 11 | /** 12 | * This class holds all the extended capabilities added the oracledb connection. 13 | * 14 | * @author Sagie Gur-Ari 15 | * @class Connection 16 | * @public 17 | */ 18 | 19 | /** 20 | * Returns only the required bind params based on the provided SQL. 21 | * 22 | * @function 23 | * @memberof! Connection 24 | * @private 25 | * @param {String} sql - The SQL using the bind params 26 | * @param {Object} bindParams - The bind parameters used to specify the values for the columns, used by all execute operations 27 | * @param {Object} [options] - The execute options 28 | * @returns {Object} The specific SQL bind params 29 | */ 30 | function getBindParams(sql, bindParams, options) { 31 | const operationBindParams = {}; 32 | 33 | let keys; 34 | const lobParams = {}; 35 | if (options && options.lobMetaInfo) { 36 | keys = Object.keys(options.lobMetaInfo); 37 | 38 | for (let index = 0; index < keys.length; index++) { 39 | lobParams[options.lobMetaInfo[keys[index]]] = true; 40 | } 41 | } 42 | 43 | keys = Object.keys(bindParams); 44 | 45 | for (let index = 0; index < keys.length; index++) { 46 | const param = keys[index]; 47 | 48 | if ((sql.indexOf(':' + param) !== -1) || lobParams[param]) { 49 | operationBindParams[param] = bindParams[param]; 50 | } 51 | } 52 | 53 | return operationBindParams; 54 | } 55 | 56 | /*eslint-disable valid-jsdoc*/ 57 | //jscs:disable jsDoc 58 | /** 59 | * The UPSERT oracledb extension gets 3 SQL statements.
60 | * It first queries the database for existing data, based on the output, it either runs INSERT or UPDATE SQL.
61 | * If it runs the INSERT and it fails on unique constraint, it will also run the UPDATE.
62 | * The output in the callback is the output of the INSERT/UPDATE operation. 63 | * 64 | * @function 65 | * @memberof! Connection 66 | * @public 67 | * @param {Object} sqls - Holds all required SQLs to support the UPSERT capability 68 | * @param {String} sqls.query - The SELECT SQL statement 69 | * @param {String} sqls.insert - The INSERT SQL statement 70 | * @param {String} sqls.update - The UPDATE SQL statement 71 | * @param {Object} bindParams - The bind parameters used to specify the values for the columns, used by all execute operations (arrays not supported, only named bind params) 72 | * @param {Object} [options] - Used by all execute operations 73 | * @param {AsyncCallback} [callback] - Invoked once the UPSERT is done with either an error or the output 74 | * @returns {Promise} In case of no callback provided in input and promise is supported, this function will return a promise 75 | * @example 76 | * ```js 77 | * connection.upsert({ 78 | * query: 'SELECT ID FROM MY_DATA WHERE ID = :id', 79 | * insert: 'INSERT INTO MY_DATA (ID, NAME) VALUES (:id, :name)', 80 | * update: 'UPDATE MY_DATA SET NAME = :name WHERE ID = :id' 81 | * }, { 82 | * id: 110, 83 | * name: 'new name' 84 | * }, { 85 | * autoCommit: false 86 | * }, function onUpsert(error, results) { 87 | * if (error) { 88 | * //handle error... 89 | * } else { 90 | * console.log('rows affected: ', results.rowsAffected); 91 | * 92 | * //continue flow... 93 | * } 94 | * }); 95 | * ``` 96 | */ 97 | const upsert = function (sqls, bindParams, options, callback) { 98 | /*eslint-disable no-invalid-this*/ 99 | const self = this; 100 | /*eslint-enable no-invalid-this*/ 101 | 102 | if (!callback) { 103 | callback = options; 104 | options = null; 105 | } 106 | 107 | bindParams = bindParams || {}; 108 | options = options || {}; 109 | 110 | if (Array.isArray(bindParams)) { 111 | callback(new Error('Array type bind params are not supported.')); 112 | } else { 113 | let upsertResult; 114 | let runUpdate; 115 | 116 | self.run([ 117 | function query(asyncCallback) { 118 | //set/add query options 119 | options.maxRows = 1; 120 | options.resultSet = false; 121 | 122 | const operationBindParams = getBindParams(sqls.query, bindParams); 123 | 124 | self.query(sqls.query, operationBindParams, options, function onQueryDone(error, results) { 125 | if (error) { 126 | asyncCallback(error); 127 | } else { 128 | if (results && results.length) { 129 | runUpdate = true; 130 | } 131 | 132 | asyncCallback(); 133 | } 134 | }); 135 | }, 136 | function insert(asyncCallback) { 137 | if (runUpdate) { 138 | asyncCallback(); 139 | } else { 140 | const operationBindParams = getBindParams(sqls.insert, bindParams, options); 141 | 142 | self.insert(sqls.insert, operationBindParams, options, function onInsertDone(error, results) { 143 | if (error) { 144 | if (error.message && (error.message.indexOf('ORA-00001') !== -1)) { //INSERT failed on unique constraint so try to UPDATE instead 145 | runUpdate = true; 146 | asyncCallback(); 147 | } else { 148 | asyncCallback(error); 149 | } 150 | } else { 151 | if (results && results.rowsAffected) { 152 | upsertResult = results; 153 | } else { 154 | runUpdate = true; 155 | } 156 | 157 | asyncCallback(); 158 | } 159 | }); 160 | } 161 | }, 162 | function update(asyncCallback) { 163 | if (runUpdate) { 164 | const operationBindParams = getBindParams(sqls.update, bindParams, options); 165 | 166 | self.update(sqls.update, operationBindParams, options, function onUpdateDone(error, results) { 167 | if (error) { 168 | asyncCallback(error); 169 | } else { 170 | let upsertError; 171 | if (results && results.rowsAffected) { 172 | upsertResult = results; 173 | } else { 174 | upsertError = new Error('No rows updated.'); 175 | } 176 | 177 | asyncCallback(upsertError); 178 | } 179 | }); 180 | } else { 181 | asyncCallback(); 182 | } 183 | } 184 | ], { 185 | sequence: true 186 | }, function onUpsertDone(error) { 187 | callback(error, upsertResult); 188 | }); 189 | } 190 | }; 191 | //jscs:enable jsDoc 192 | /*eslint-enable valid-jsdoc*/ 193 | 194 | const SimpleOracleDB = require('simple-oracledb'); 195 | SimpleOracleDB.addExtension('connection', 'upsert', upsert); 196 | -------------------------------------------------------------------------------- /test/spec/integration-spec.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const asyncLib = require('async'); 4 | const chai = require('chai'); 5 | const assert = chai.assert; 6 | 7 | describe('Integration Tests', function () { 8 | const self = this; 9 | 10 | let integrated = true; 11 | const connAttrs = { 12 | user: process.env.TEST_ORACLE_USER, 13 | password: process.env.TEST_ORACLE_PASSWORD, 14 | connectString: process.env.TEST_ORACLE_CONNECTION_STRING 15 | }; 16 | 17 | if ((!connAttrs.user) || (!connAttrs.password) || (!connAttrs.connectString)) { 18 | integrated = false; 19 | } 20 | 21 | if (!integrated) { 22 | it('empty', function () { 23 | return undefined; 24 | }); 25 | } else { 26 | const oracledb = require('oracledb'); 27 | 28 | oracledb.autoCommit = true; 29 | 30 | const simpleOracleDB = require('simple-oracledb'); 31 | require('../../'); //load upsert 32 | 33 | simpleOracleDB.extend(oracledb); 34 | 35 | const end = function (done, connection) { 36 | if (connection) { 37 | connection.release(); 38 | } 39 | 40 | setTimeout(done, 10); 41 | }; 42 | 43 | let testPool; 44 | const initDB = function (tableName, data, cb) { 45 | oracledb.getConnection(connAttrs, function (connErr, connection) { 46 | data = data || []; 47 | 48 | if (connErr) { 49 | console.error(connErr); 50 | setTimeout(function () { 51 | assert.fail('UNABLE TO OPEN DB CONNECTION.'); 52 | }, 100); 53 | } else { 54 | connection.execute('DROP TABLE ' + tableName, [], function () { 55 | connection.execute('CREATE TABLE ' + tableName + ' (ID NUMBER PRIMARY KEY, NAME constCHAR2(250), LOB_DATA CLOB)', [], function (createError) { 56 | if (createError) { 57 | console.error(createError); 58 | assert.fail('UNABLE TO CREATE DB TABLE: ' + tableName); 59 | } else { 60 | const func = []; 61 | data.forEach(function (rowData) { 62 | func.push(function (asyncCB) { 63 | if (!rowData.LOB_DATA) { 64 | rowData.LOB_DATA = undefined; 65 | } 66 | 67 | connection.execute('INSERT INTO ' + tableName + ' (ID, NAME, LOB_DATA) VALUES (:ID, :NAME, :LOB_DATA)', rowData, function (insertErr) { 68 | if (insertErr) { 69 | asyncCB(insertErr); 70 | } else { 71 | asyncCB(null, rowData); 72 | } 73 | }); 74 | }); 75 | }); 76 | 77 | asyncLib.series(func, function (asynErr) { 78 | connection.release(function (rerr) { 79 | if (asynErr) { 80 | console.error(asynErr); 81 | assert.fail('UNABLE TO CREATE DB POOL.'); 82 | } else if (rerr) { 83 | console.error('release error: ', rerr); 84 | } else if (testPool) { 85 | cb(testPool); 86 | } else { 87 | oracledb.createPool(connAttrs, function (perr, newPool) { 88 | if (perr) { 89 | console.error(perr); 90 | assert.fail('UNABLE TO CREATE DB POOL.'); 91 | } else { 92 | testPool = newPool; 93 | cb(testPool); 94 | } 95 | }); 96 | } 97 | }); 98 | }); 99 | } 100 | }); 101 | }); 102 | } 103 | }); 104 | }; 105 | 106 | self.timeout(30000); 107 | 108 | describe('upsert', function () { 109 | const createSQLs = function (table) { 110 | return { 111 | query: 'SELECT ID FROM ' + table + ' WHERE ID = :id', 112 | insert: 'INSERT INTO ' + table + ' (ID, NAME, LOB_DATA) VALUES (:id, :name, EMPTY_CLOB())', 113 | update: 'UPDATE ' + table + ' SET NAME = :name, LOB_DATA = EMPTY_CLOB() WHERE ID = :id' 114 | }; 115 | }; 116 | 117 | it('empty table', function (done) { 118 | const table = 'TEST_ORA1'; 119 | initDB(table, null, function (pool) { 120 | pool.getConnection(function (err, connection) { 121 | assert.isNull(err); 122 | 123 | connection.query('SELECT * FROM ' + table, function (error1, jsRows) { 124 | assert.isNull(error1); 125 | assert.deepEqual([], jsRows); 126 | 127 | connection.upsert(createSQLs(table), { 128 | id: 110, 129 | name: 'new name', 130 | lobData: 'some long CLOB text here' 131 | }, { 132 | autoCommit: true, 133 | lobMetaInfo: { 134 | LOB_DATA: 'lobData' 135 | } 136 | }, function onUpsert(error2, results2) { 137 | assert.isNull(error2); 138 | assert.equal(results2.rowsAffected, 1); 139 | 140 | connection.query('SELECT * FROM ' + table, function (error3, jsRows3) { 141 | assert.isNull(error3); 142 | assert.deepEqual([ 143 | { 144 | ID: 110, 145 | NAME: 'new name', 146 | LOB_DATA: 'some long CLOB text here' 147 | } 148 | ], jsRows3); 149 | 150 | end(done, connection); 151 | }); 152 | }); 153 | }); 154 | }); 155 | }); 156 | }); 157 | 158 | it('existing row table', function (done) { 159 | const table = 'TEST_ORA2'; 160 | initDB(table, [ 161 | { 162 | id: 110, 163 | name: 'old name' 164 | } 165 | ], function (pool) { 166 | pool.getConnection(function (err, connection) { 167 | assert.isNull(err); 168 | 169 | connection.query('SELECT * FROM ' + table, function (error1, jsRows) { 170 | assert.isNull(error1); 171 | assert.deepEqual([ 172 | { 173 | ID: 110, 174 | NAME: 'old name', 175 | LOB_DATA: null 176 | } 177 | ], jsRows); 178 | 179 | connection.upsert(createSQLs(table), { 180 | id: 110, 181 | name: 'new name', 182 | lobData: 'some long CLOB text here' 183 | }, { 184 | autoCommit: true, 185 | lobMetaInfo: { 186 | LOB_DATA: 'lobData' 187 | } 188 | }, function onUpsert(error2, results2) { 189 | assert.isNull(error2); 190 | assert.equal(results2.rowsAffected, 1); 191 | 192 | connection.query('SELECT * FROM ' + table, function (error3, jsRows3) { 193 | assert.isNull(error3); 194 | assert.deepEqual([ 195 | { 196 | ID: 110, 197 | NAME: 'new name', 198 | LOB_DATA: 'some long CLOB text here' 199 | } 200 | ], jsRows3); 201 | 202 | end(done, connection); 203 | }); 204 | }); 205 | }); 206 | }); 207 | }); 208 | }); 209 | }); 210 | } 211 | }); 212 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /test/spec/upsert-spec.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const chai = require('chai'); 4 | const assert = chai.assert; 5 | const PromiseLib = global.Promise || require('promiscuous'); 6 | const SimpleOracleDB = require('simple-oracledb'); 7 | require('../../lib/upsert'); 8 | 9 | describe('upsert Tests', function () { 10 | const asArray = function (args) { 11 | return Array.prototype.slice.call(args, 0); 12 | }; 13 | 14 | const createOracleDB = function () { 15 | const failFunc = function () { 16 | assert.fail(); 17 | }; 18 | 19 | const oracledb = { 20 | createPool() { 21 | return undefined; 22 | }, 23 | getConnection() { 24 | const args = asArray(arguments); 25 | const callback = args[args.length - 1]; 26 | callback(null, { 27 | query: failFunc, 28 | insert: failFunc, 29 | update: failFunc 30 | }); 31 | } 32 | }; 33 | 34 | SimpleOracleDB.extend(oracledb); 35 | 36 | return oracledb; 37 | }; 38 | 39 | describe('extension', function () { 40 | it('valid', function (done) { 41 | const oracledb = createOracleDB(); 42 | 43 | oracledb.getConnection({}, function (error, connection) { 44 | assert.isNull(error); 45 | assert.isFunction(connection.upsert); 46 | 47 | done(); 48 | }); 49 | }); 50 | }); 51 | 52 | describe('upsert', function () { 53 | it('no options', function (done) { 54 | const oracledb = createOracleDB(); 55 | 56 | oracledb.getConnection({}, function (connectionError, connection) { 57 | assert.isNull(connectionError); 58 | 59 | connection.query = function () { 60 | const args = asArray(arguments); 61 | args[args.length - 1](new Error('test error')); 62 | }; 63 | 64 | connection.upsert({}, {}, function (error, result) { 65 | assert.isDefined(error); 66 | assert.equal(error.message, 'test error'); 67 | assert.isUndefined(result); 68 | 69 | done(); 70 | }); 71 | }); 72 | }); 73 | 74 | it('null bind params', function (done) { 75 | const oracledb = createOracleDB(); 76 | 77 | oracledb.getConnection({}, function (connectionError, connection) { 78 | assert.isNull(connectionError); 79 | 80 | connection.query = function () { 81 | arguments[arguments.length - 1](new Error('test error')); 82 | }; 83 | 84 | connection.upsert({}, null, function (error, result) { 85 | assert.isDefined(error); 86 | assert.equal(error.message, 'test error'); 87 | assert.isUndefined(result); 88 | 89 | done(); 90 | }); 91 | }); 92 | }); 93 | 94 | it('array bind params', function (done) { 95 | const oracledb = createOracleDB(); 96 | 97 | oracledb.getConnection({}, function (connectionError, connection) { 98 | assert.isNull(connectionError); 99 | 100 | connection.upsert({}, [], function (error, result) { 101 | assert.isDefined(error); 102 | assert.equal(error.message, 'Array type bind params are not supported.'); 103 | assert.isUndefined(result); 104 | 105 | done(); 106 | }); 107 | }); 108 | }); 109 | 110 | it('query error', function (done) { 111 | const oracledb = createOracleDB(); 112 | 113 | oracledb.getConnection({}, function (connectionError, connection) { 114 | assert.isNull(connectionError); 115 | 116 | connection.query = function () { 117 | arguments[arguments.length - 1](new Error('test query error')); 118 | }; 119 | 120 | connection.upsert({}, {}, {}, function (error, result) { 121 | assert.isDefined(error); 122 | assert.equal(error.message, 'test query error'); 123 | assert.isUndefined(result); 124 | 125 | done(); 126 | }); 127 | }); 128 | }); 129 | 130 | it('insert general error', function (done) { 131 | const oracledb = createOracleDB(); 132 | 133 | oracledb.getConnection({}, function (connectionError, connection) { 134 | assert.isNull(connectionError); 135 | 136 | connection.query = function () { 137 | arguments[arguments.length - 1](null, []); 138 | }; 139 | 140 | connection.insert = function () { 141 | arguments[arguments.length - 1](new Error('test insert error')); 142 | }; 143 | 144 | connection.upsert({}, {}, {}, function (error, result) { 145 | assert.isDefined(error); 146 | assert.equal(error.message, 'test insert error'); 147 | assert.isUndefined(result); 148 | 149 | done(); 150 | }); 151 | }); 152 | }); 153 | 154 | it('insert unique constraint error and update error', function (done) { 155 | const oracledb = createOracleDB(); 156 | 157 | oracledb.getConnection({}, function (connectionError, connection) { 158 | assert.isNull(connectionError); 159 | 160 | connection.query = function () { 161 | arguments[arguments.length - 1](null, []); 162 | }; 163 | 164 | connection.insert = function () { 165 | arguments[arguments.length - 1](new Error('test ORA-00001 error')); 166 | }; 167 | 168 | connection.update = function () { 169 | arguments[arguments.length - 1](new Error('test update error')); 170 | }; 171 | 172 | connection.upsert({}, {}, {}, function (error, result) { 173 | assert.isDefined(error); 174 | assert.equal(error.message, 'test update error'); 175 | assert.isUndefined(result); 176 | 177 | done(); 178 | }); 179 | }); 180 | }); 181 | 182 | it('no insert and update error', function (done) { 183 | const oracledb = createOracleDB(); 184 | 185 | oracledb.getConnection({}, function (connectionError, connection) { 186 | assert.isNull(connectionError); 187 | 188 | connection.query = function () { 189 | arguments[arguments.length - 1](null, [{}]); 190 | }; 191 | 192 | connection.update = function () { 193 | arguments[arguments.length - 1](new Error('test update2 error')); 194 | }; 195 | 196 | connection.upsert({}, {}, {}, function (error, result) { 197 | assert.isDefined(error); 198 | assert.equal(error.message, 'test update2 error'); 199 | assert.isUndefined(result); 200 | 201 | done(); 202 | }); 203 | }); 204 | }); 205 | 206 | it('no insert and update error, using promise', function (done) { 207 | const oracledb = createOracleDB(); 208 | 209 | oracledb.getConnection({}, function (connectionError, connection) { 210 | assert.isNull(connectionError); 211 | 212 | connection.query = function () { 213 | arguments[arguments.length - 1](null, [{}]); 214 | }; 215 | 216 | connection.update = function () { 217 | arguments[arguments.length - 1](new Error('test update2 error')); 218 | }; 219 | 220 | global.Promise = PromiseLib; 221 | 222 | const promise = connection.upsert({}, {}, {}); 223 | 224 | promise.then(function () { 225 | assert.fail(); 226 | }).catch(function (error) { 227 | assert.isDefined(error); 228 | assert.equal(error.message, 'test update2 error'); 229 | 230 | done(); 231 | }); 232 | }); 233 | }); 234 | 235 | it('insert valid', function (done) { 236 | const oracledb = createOracleDB(); 237 | 238 | oracledb.getConnection({}, function (connectionError, connection) { 239 | assert.isNull(connectionError); 240 | 241 | connection.query = function () { 242 | arguments[arguments.length - 1](null, []); 243 | }; 244 | 245 | connection.insert = function () { 246 | arguments[arguments.length - 1](null, { 247 | rowsAffected: 1 248 | }); 249 | }; 250 | 251 | connection.upsert({}, {}, {}, function (error, result) { 252 | assert.isNull(error); 253 | assert.deepEqual(result, { 254 | rowsAffected: 1 255 | }); 256 | 257 | done(); 258 | }); 259 | }); 260 | }); 261 | 262 | it('insert valid, using promise', function (done) { 263 | const oracledb = createOracleDB(); 264 | 265 | oracledb.getConnection({}, function (connectionError, connection) { 266 | assert.isNull(connectionError); 267 | 268 | connection.query = function () { 269 | arguments[arguments.length - 1](null, []); 270 | }; 271 | 272 | connection.insert = function () { 273 | arguments[arguments.length - 1](null, { 274 | rowsAffected: 1 275 | }); 276 | }; 277 | 278 | global.Promise = PromiseLib; 279 | 280 | const promise = connection.upsert({}, {}, {}); 281 | 282 | promise.then(function (result) { 283 | assert.deepEqual(result, { 284 | rowsAffected: 1 285 | }); 286 | 287 | done(); 288 | }).catch(function () { 289 | assert.fail(); 290 | }); 291 | }); 292 | }); 293 | 294 | it('row exists, update valid', function (done) { 295 | const oracledb = createOracleDB(); 296 | 297 | oracledb.getConnection({}, function (connectionError, connection) { 298 | assert.isNull(connectionError); 299 | 300 | connection.query = function () { 301 | arguments[arguments.length - 1](null, [{}]); 302 | }; 303 | 304 | connection.update = function () { 305 | arguments[arguments.length - 1](null, { 306 | rowsAffected: 1 307 | }); 308 | }; 309 | 310 | connection.upsert({ 311 | query: 'SELECT * FROM MY_TABLE WHERE A = :a', 312 | update: 'UPDATE MY_TABLE SET B = :b, MY_CLOB = EMPTY_CLOB() WHERE A = :a' 313 | }, { 314 | a: 1, 315 | b: 2, 316 | myClob: 3 317 | }, { 318 | lobMetaInfo: { 319 | MY_CLOB: 'myClob' 320 | } 321 | }, function (error, result) { 322 | assert.isNull(error); 323 | assert.deepEqual(result, { 324 | rowsAffected: 1 325 | }); 326 | 327 | done(); 328 | }); 329 | }); 330 | }); 331 | 332 | it('row exists, update valid, using promise', function (done) { 333 | const oracledb = createOracleDB(); 334 | 335 | oracledb.getConnection({}, function (connectionError, connection) { 336 | assert.isNull(connectionError); 337 | 338 | connection.query = function () { 339 | arguments[arguments.length - 1](null, [{}]); 340 | }; 341 | 342 | connection.update = function () { 343 | arguments[arguments.length - 1](null, { 344 | rowsAffected: 1 345 | }); 346 | }; 347 | 348 | global.Promise = PromiseLib; 349 | 350 | const promise = connection.upsert({ 351 | query: 'SELECT * FROM MY_TABLE WHERE A = :a', 352 | update: 'UPDATE MY_TABLE SET B = :b, MY_CLOB = EMPTY_CLOB() WHERE A = :a' 353 | }, { 354 | a: 1, 355 | b: 2, 356 | myClob: 3 357 | }, { 358 | lobMetaInfo: { 359 | MY_CLOB: 'myClob' 360 | } 361 | }); 362 | 363 | promise.then(function (result) { 364 | assert.deepEqual(result, { 365 | rowsAffected: 1 366 | }); 367 | 368 | done(); 369 | }).catch(function () { 370 | assert.fail(); 371 | }); 372 | }); 373 | }); 374 | 375 | it('row exists, update did not modify any row', function (done) { 376 | const oracledb = createOracleDB(); 377 | 378 | oracledb.getConnection({}, function (connectionError, connection) { 379 | assert.isNull(connectionError); 380 | 381 | connection.query = function () { 382 | arguments[arguments.length - 1](null, [{}]); 383 | }; 384 | 385 | connection.update = function () { 386 | arguments[arguments.length - 1](null, { 387 | rowsAffected: 0 388 | }); 389 | }; 390 | 391 | connection.upsert({}, {}, {}, function (error, result) { 392 | assert.isDefined(error); 393 | assert.equal(error.message, 'No rows updated.'); 394 | assert.isUndefined(result); 395 | 396 | done(); 397 | }); 398 | }); 399 | }); 400 | 401 | it('insert unique constraint error and update valid', function (done) { 402 | const oracledb = createOracleDB(); 403 | 404 | oracledb.getConnection({}, function (connectionError, connection) { 405 | assert.isNull(connectionError); 406 | 407 | connection.query = function () { 408 | arguments[arguments.length - 1](null, []); 409 | }; 410 | 411 | let insertCalled = false; 412 | connection.insert = function () { 413 | insertCalled = true; 414 | 415 | arguments[arguments.length - 1](new Error('test ORA-00001 error')); 416 | }; 417 | 418 | connection.update = function () { 419 | arguments[arguments.length - 1](null, { 420 | rowsAffected: 1 421 | }); 422 | }; 423 | 424 | connection.upsert({}, {}, {}, function (error, result) { 425 | assert.isNull(error); 426 | assert.isTrue(insertCalled); 427 | assert.deepEqual(result, { 428 | rowsAffected: 1 429 | }); 430 | 431 | done(); 432 | }); 433 | }); 434 | }); 435 | 436 | it('insert no impact and update valid', function (done) { 437 | const oracledb = createOracleDB(); 438 | 439 | oracledb.getConnection({}, function (connectionError, connection) { 440 | assert.isNull(connectionError); 441 | 442 | connection.query = function () { 443 | const args = asArray(arguments); 444 | assert.equal(args[0], 'select 1'); 445 | 446 | args[args.length - 1](null, []); 447 | }; 448 | 449 | let insertCalled = false; 450 | connection.insert = function () { 451 | const args = asArray(arguments); 452 | assert.equal(args[0], 'insert 2'); 453 | 454 | insertCalled = true; 455 | 456 | args[args.length - 1](null, { 457 | rowsAffected: 0 458 | }); 459 | }; 460 | 461 | connection.update = function () { 462 | const args = asArray(arguments); 463 | assert.equal(args[0], 'update 3'); 464 | 465 | args[args.length - 1](null, { 466 | rowsAffected: 1 467 | }); 468 | }; 469 | 470 | connection.upsert({ 471 | query: 'select 1', 472 | insert: 'insert 2', 473 | update: 'update 3' 474 | }, {}, {}, function (error, result) { 475 | assert.isNull(error); 476 | assert.isTrue(insertCalled); 477 | assert.deepEqual(result, { 478 | rowsAffected: 1 479 | }); 480 | 481 | done(); 482 | }); 483 | }); 484 | }); 485 | }); 486 | }); 487 | --------------------------------------------------------------------------------