some work on the new knex architecture

This commit is contained in:
Tim Griesser 2013-09-04 20:47:27 -04:00
parent a59baeb01f
commit 2bf076f15a
3 changed files with 149 additions and 162 deletions

49
clients/base.js Normal file
View File

@ -0,0 +1,49 @@
(function(define) {
"use strict";
define(function(require, exports) {
var Helpers = require('../lib/helpers').Helpers;
// The `ClientBase` is assumed as the object that all database `clients`
// inherit from, and is used in an `instanceof` check when initializing the
// library. If you wish to write or customize an adapter, just inherit from
// this base, with ClientBase.extend, and you're good to go.
var ClientBase = function() {};
// The methods assumed when building a client.
ClientBase.prototype = {
// The biggest method of the client, the `query` is used to
query: function() {},
// Retrieves a connection from the connection pool,
// returning a promise.
getConnection: function() {},
// Releases a connection from the connection pool,
// returning a promise.
releaseConnection: function(conn) {},
// Begins a transaction statement on the instance,
// resolving with the connection of the current transaction.
startTransaction: function() {},
// Finishes a transaction, taking the `type`
finishTransaction: function(type, trans, dfd, msg) {},
// The pool defaults.
poolDefaults: function() {}
};
ClientBase.extend = Helpers.extend;
exports.ClientBase = ClientBase;
});
})(
typeof define === 'function' && define.amd ? define : function(factory) { factory(require, exports);
});

250
knex.js
View File

@ -1,5 +1,5 @@
// Knex.js 0.2.6 // Knex.js 0.4.0
//
// (c) 2013 Tim Griesser // (c) 2013 Tim Griesser
// Knex may be freely distributed under the MIT license. // Knex may be freely distributed under the MIT license.
// For details and documentation: // For details and documentation:
@ -10,185 +10,119 @@
define(function(require, exports, module) { define(function(require, exports, module) {
// Required dependencies.
var _ = require('underscore'); var _ = require('underscore');
var when = require('when'); var when = require('when');
var Common = require('./lib/common').Common;
var Helpers = require('./lib/helpers').Helpers;
// `Knex` is the root namespace and a chainable function: `Knex('tableName')` var Raw = require('./lib/raw').Raw;
var Knex = function(table) { var Transaction = require('./lib/transaction').Transaction;
if (!Knex.Instances['main']) { var Builder = require('./lib/builder').Builder;
throw new Error('The Knex instance has not been initialized yet.'); var Interface = require('./lib/builder/interface').Interface;
var Schema = require('./lib/schema').Schema;
var ClientBase = require('./clients/clientbase').ClientBase;
// The `Knex` module, taking either a fully initialized
// database client, or a configuration to initialize one. This is something
// you'll typically only want to call once per application cycle.
var Knex = function(client) {
// If the client isn't actually a client, we need to configure it into one.
// On the client, this isn't acceptable, since we need to return immediately
// rather than wait on an async load of a client library.
if (!client instanceof ClientBase) {
if (typeof define === 'function' && define.amd) {
throw new Error('A valid `Knex` client must be passed into the Knex constructor.');
} else {
var clientName = client.client;
if (!Clients[clientName]) {
throw new Error(clientName + ' is not a valid Knex client, did you misspell it?');
} }
return Knex.Instances['main'](table); var ClientCtor = require(Clients[clientName]);
client = new ClientCtor(_.omit(options, 'client'));
}
}
// Enables the `Knex('tableName')` shorthand syntax.
var instance = function(tableName) {
return instance.builder(tableName);
}; };
// Keep in sync with package.json // Main namespaces for key library components.
Knex.VERSION = '0.2.6'; instance.schema = {};
Knex.Builder = require('./lib/builder').Builder; instance.migrate = {};
Knex.JoinClause = require('./lib/joinclause').JoinClause;
// Knex.Transaction // Enable the `Builder('tableName')` syntax, as is used in the main `Knex('tableName')`.
// --------- instance.builder = function(tableName) {
Knex.Transaction = function(container) { var builder = new Builder(instance);
if (!Knex.Instances['main']) { return tableName ? builder.table(tableName) : builder;
throw new Error('The Knex instance has not been initialized yet.');
}
return transaction.call(Knex.Instances['main'], container);
}; };
var transaction = require('./lib/transaction').transaction; // Attach each of the `Builder` "interface" methods direcly onto
// the `Knex` object, for ease of use when creating a new query builder chain:
// Knex.Schema // `Knex.select('*').from('tableName').then(...`
// --------- // `Knex.insert(values).into('tableName').then(...`
// `Knex.update(values).then(...`
var initSchema = function(Target, client) { _.each(Interface, function(val, key) {
instance[key] = function() {
// Top level object for Schema related functions var builder = new Builder(instance);
var Schema = Target.Schema = {}; return builder[key].apply(builder, arguments);
// Attach main static methods, which passthrough to the
// SchemaBuilder instance methods
_.each(['hasTable', 'hasColumn', 'createTable', 'table', 'dropTable', 'renameTable', 'dropTableIfExists'], function(method) {
Schema[method] = function() {
var args = _.toArray(arguments);
var builder = new Knex.SchemaBuilder(args[0]);
builder.client = client;
builder.grammar = client.schemaGrammar;
return SchemaInterface[method].apply(builder, args.slice(1));
}; };
}); });
// Attach each of the `Schema` "interface" methods directly onto to `Knex.Schema` namespace:
// `Knex.Schema.table('tableName', function() {...`
// `Knex.Schema.createTable('tableName', function() {...`
// `Knex.Schema.dropTableIfExists('tableName');`
_.each(SchemaInterface, function(val, key) {
instance.schema[key] = function() {
var schemaBuilder = new SchemaBuilder(instance);
schemaBuilder.table = _.first(arguments);
return schemaBuilder[key].apply(schemaBuilder, _.rest(arguments));
};
});
// Attach each of the `Migrate` "interface" methods directly on to
_.each(MigrateInterface, function(val, key) {
instance.migrate[key] = function() {
var migrateBuilder = new MigrateBuilder(instance);
return MigrateBuilder[key].apply(migrateBuilder, arguments);
};
});
// Method to run a new `Raw` query on the current client.
instance.raw = function() {
var raw = new Raw(instance);
return raw.query.apply(raw, arguments);
}; };
// All of the Schame methods that should be called with a // Keep a reference to the current client.
// `SchemaBuilder` context, to disallow calling more than one method at once. instance.client = client;
var SchemaInterface = require('./lib/schemainterface').SchemaInterface;
// Knex.SchemaBuilder // Keep in sync with package.json
// -------- instance.VERSION = '0.5.0';
Knex.SchemaBuilder = require('./lib/schemabuilder').SchemaBuilder;
// Knex.Migrate // Runs a new transaction, taking a container and
// -------- instance.transaction = function(container) {
Knex.Migrate = require('./lib/migrate').Migrate; var transaction = new Transaction(instance);
return transaction.run(container);
// Knex.Raw
// -------
// Helpful for injecting a snippet of raw SQL into a
// `Knex` block... in most cases, we'll check if the value
// is an instanceof Raw, and if it is, use the supplied value.
Knex.Raw = function(sql, bindings) {
if (!Knex.Instances['main']) {
throw new Error('The Knex instance has not been initialized yet.');
}
return Knex.Instances['main'].Raw(sql, bindings);
}; };
var Raw = require('./lib/raw').Raw; // Return the new Knex instance.
_.extend(Raw.prototype, Common); return instance;
// Knex.Initialize
// -------
// Takes a hash of options to initialize the database
// connection. The `client` is required to choose which client
// path above is loaded, or to specify a custom path to a client.
// Other options, such as `connection` or `pool` are passed
// into `client.initialize`.
Knex.Initialize = function(name, options) {
var Target, ClientCtor, client;
// A name for the connection isn't required in
// cases where there is only a single connection.
if (_.isObject(name)) {
options = name;
name = 'main';
}
// Don't try to initialize the same `name` twice... If necessary,
// delete the instance from `Knex.Instances`.
if (Knex.Instances[name]) {
throw new Error('An instance named ' + name + ' already exists.');
}
client = options.client;
if (!client) throw new Error('The client is required to use Knex.');
// Checks if this is a default client. If it's not,
// that means it's a custom lib, set the object to the client.
if (_.isString(client)) {
client = client.toLowerCase();
try {
ClientCtor = require(Clients[client]);
} catch (e) {
throw new Error(client + ' is not a valid Knex client, did you misspell it?');
}
} else {
ClientCtor = client;
}
// Creates a new instance of the db client, passing the name and options.
client = new ClientCtor(name, _.omit(options, 'client'));
// If this is named "default" then we're setting this on the Knex
Target = function(table) {
var builder = new Knex.Builder(client);
return table ? builder.from(table) : builder;
}; };
// Inherit static properties, without any that don't apply except var Clients = Knex.Clients = {
// on the "root" `Knex`. 'mysql' : './clients/mysql.js',
_.extend(Target, _.omit(Knex, 'Initialize', 'Instances', 'VERSION')); 'pg' : './clients/postgres.js',
'postgres' : './clients/postgres.js',
// Initialize the schema builder methods. 'sqlite' : './clients/sqlite3.js',
if (name === 'main') { 'sqlite3' : './clients/sqlite3.js'
initSchema(Knex, client);
Knex.client = client;
}
initSchema(Target, client);
// Specifically set the client on the current target.
Target.client = client;
Target.instanceName = name;
// Setup the transacting function properly for this connection.
Target.Transaction = function(handler) {
return transaction.call(this, handler);
}; };
// Executes a Raw query. // Used primarily to type-check a potential `Knex` client in `Bookshelf.js`,
Target.Raw = function(sql, bindings) { // by examining whether the object's `client` is an `instanceof Knex.ClientBase`.
var raw = new Raw(sql, bindings); Knex.ClientBase = ClientBase;
raw.client = client;
return raw;
};
// Add this instance to the global `Knex` instances, and return. // finally, export the `Knex` object for node and the browser.
Knex.Instances[name] = Target;
return Target;
};
// Default client paths, located in the `./clients` directory.
var Clients = {
'mysql' : './clients/server/mysql.js',
'pg' : './clients/server/postgres.js',
'postgres' : './clients/server/postgres.js',
'sqlite' : './clients/server/sqlite3.js',
'sqlite3' : './clients/server/sqlite3.js'
};
// Named instances of Knex, presumably with different database
// connections, the main instance being named "main"...
Knex.Instances = {};
// Export the Knex module
module.exports = Knex; module.exports = Knex;
}); });

View File

@ -7,9 +7,13 @@ define(function(require, exports) {
var when = require('when'); var when = require('when');
var _ = require('underscore'); var _ = require('underscore');
var transaction = function(container) { var Transaction = function(instance) {
this.knex = instance;
};
var client = this.client; Transaction.prototype.run = function(container) {
var client = this.knex.client;
return client.startTransaction().then(function(connection) { return client.startTransaction().then(function(connection) {
@ -40,7 +44,7 @@ define(function(require, exports) {
}); });
}; };
exports.transaction = transaction; exports.Transaction = Transaction;
}); });