jbrumwell / mock-knex

A mock knex adapter for simulating a database during testing
MIT License
240 stars 71 forks source link

Tracking `transaction` context #26

Closed vellotis closed 8 years ago

vellotis commented 8 years ago

It would be great if transaction context for query could be accessed through tracker event.

The query dialect client has a instance property txid if transaction is used. This can be accessed the same way by query mock.

I would implement it and do a PR, but what would be the best practise to implement it? Set it as tracker emitted query argument property, property of its options proeprty or as an additional event emit argument? I think the last one would be suitable as the query argument is returned by promise. So the new signature for track method would be

Queries.prototype.track = function track(query, trx, resolver) {
  var step;

  if (this.tracker.tracking) {
    query.response = function response(result) {
      query.result = result;
      resolver(query);
    };

    delete query.result;

    step = this.queries.push(query);
    this.tracker.emit('query', query, step, trx);
  } else {
    resolver();
  }
};

And the client query method must be something like this

client.constructor.prototype._query = client._query = function(connection, obj) {
  return new Promise(function(resolver, rejecter) {
    tracker.queries.track(obj, this.txid, resolver);
  });
};

and knex _query method must be something like this

client._query = function(connection, obj) {
  return new Promise(function(resolver, rejecter) {
    tracker.queries.track(obj, this.txid, resolver);
  });
};

As a result the query context trx could be accessible this way:

tracker.on('query', function (query, step, trx) { /* some logic */ };

Is it considerable? BR

vellotis commented 8 years ago

Sadly suggested solution seems to be valid only for v.0.10.x versions. Have to investigate further for solution for older knex versions.

jbrumwell commented 8 years ago

@vellotis thank you for your contributions I am traveling until the 14th but will have a look at it all then :)

jbrumwell commented 8 years ago

If you have time to run the release/0.3.3 branch the query object now has a transacting parameter unfortunately we cannot differentiate between different transactions.

vellotis commented 8 years ago

Thanks @jbrumwell