Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions lib/bigquery/table.js
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,9 @@ Table.prototype.import = function(source, metadata, callback) {
* @resource [Tabledata: insertAll API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/tabledata/insertAll}
*
* @param {object|object[]} rows - The rows to insert into the table.
* @param {object=} options - Configuration object.
* @param {boolean} options.duplicates - Allow duplicate entries. Default:
* `false`
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {array} callback.insertErrors - A list of errors for insert failures.
Expand Down Expand Up @@ -897,15 +900,26 @@ Table.prototype.import = function(source, metadata, callback) {
* // recommendations on handling errors.
* }
*/
Table.prototype.insert = function(rows, callback) {
Table.prototype.insert = function(rows, options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}

var body = {
rows: arrify(rows).map(function(row) {
var rowObject = {};
// Use the stringified contents of the row as a unique insert ID.
var md5 = crypto.createHash('md5');
md5.update(JSON.stringify(row));
rowObject.insertId = md5.digest('hex');
rowObject.json = row;
var rowObject = {
json: row
};

if (!options.duplicates) {
// Prevent duplicate entries by using the `insertId` property.
// Use the stringified contents of the row as the unique ID.
var md5 = crypto.createHash('md5');
md5.update(JSON.stringify(row));
rowObject.insertId = md5.digest('hex');
}

return rowObject;
})
};
Expand Down
24 changes: 24 additions & 0 deletions test/bigquery/table.js
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,30 @@ describe('BigQuery/Table', function() {
table.insert(data, done);
});

describe('duplicates', function() {
it('should default to false', function(done) {
table.request = function(reqOpts) {
assert.deepEqual(reqOpts.json, dataApiFormat);
done();
};

table.insert(data, assert.ifError);
});

it('should not set an insertId when set to true', function(done) {
table.request = function(reqOpts) {
assert.strictEqual(reqOpts.json.rows[0].insertId, undefined);
done();
};

var options = {
duplicates: true
};

table.insert(data, options, assert.ifError);
});
});

it('should execute callback with API response', function(done) {
var apiResponse = { insertErrors: [] };

Expand Down