Socket
Socket
Sign inDemoInstall

bookshelf

Package Overview
Dependencies
Maintainers
1
Versions
87
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bookshelf - npm Package Compare versions

Comparing version 0.6.12 to 0.7.0

browser/bookshelf.js

215

bookshelf.js

@@ -1,2 +0,2 @@

// Bookshelf.js 0.6.12
// Bookshelf.js 0.7.0
// ---------------

@@ -9,70 +9,120 @@

// All external libraries needed in this scope.
var _ = require('lodash');
var Knex = require('knex');
var Bookshelf = function() {
return Bookshelf.initialize.apply(null, arguments);
};
// All local dependencies... These are the main objects that
// need to be augmented in the constructor to work properly.
var SqlModel = require('./dialects/sql/model').Model;
var SqlCollection = require('./dialects/sql/collection').Collection;
var SqlRelation = require('./dialects/sql/relation').Relation;
// Finally, the `Events`, which we've supplemented with a `triggerThen`
// method to allow for asynchronous event handling via promises. We also
// mix this into the prototypes of the main objects in the library.
var Events = require('./dialects/base/events').Events;
// Constructor for a new `Bookshelf` object, it accepts
// an active `knex` instance and initializes the appropriate
// `Model` and `Collection` constructors for use in the current instance.
var Bookshelf = function(knex) {
Bookshelf.initialize = function(knex) {
var bookshelf = {
VERSION: '0.7.0'
};
// Allows you to construct the library with either `Bookshelf(opts)`
// or `new Bookshelf(opts)`.
if (!(this instanceof Bookshelf)) {
return new Bookshelf(knex);
}
var _ = require('lodash');
var inherits = require('inherits');
var semver = require('semver');
// We've supplemented `Events` with a `triggerThen`
// method to allow for asynchronous event handling via promises. We also
// mix this into the prototypes of the main objects in the library.
var Events = require('./lib/base/events');
// All core modules required for the bookshelf instance.
var BookshelfModel = require('./lib/model');
var BookshelfCollection = require('./lib/collection');
var BookshelfRelation = require('./lib/relation');
var Errors = require('./lib/errors');
// If the knex isn't a `Knex` instance, we'll assume it's
// a compatible config object and pass it through to create a new instance.
if (!knex.client || !(knex.client instanceof Knex.ClientBase)) {
knex = new Knex(knex);
// This behavior is now deprecated.
if (_.isPlainObject(knex)) {
console.warn('Initializing Bookshelf with a config object is deprecated, please pass an initialized knex.js instance.');
knex = new require('knex')(knex);
}
var range = '>=0.6.0';
if (!semver.satisfies(knex.VERSION, range)) {
throw new Error('The knex version is ' + knex.VERSION + ' which does not satisfy the Bookshelf\'s requirement ' + range);
}
var Model = bookshelf.Model = function() {
BookshelfModel.apply(this, arguments);
};
var Collection = bookshelf.Collection = function() {
BookshelfCollection.apply(this, arguments);
};
inherits(Model, BookshelfModel);
inherits(Collection, BookshelfCollection);
_.extend(Model, BookshelfModel);
_.extend(Collection, BookshelfCollection);
Model.prototype._builder =
Collection.prototype._builder = function(tableName) {
var builder = knex(tableName);
var instance = this;
return builder.on('query', function(data) {
instance.trigger('query', data);
});
};
// The collection also references the correct `Model`, specified above, for creating
// new `Model` instances in the collection.
Collection.prototype.model = Model;
Model.prototype.Collection = Collection;
function Relation() {
BookshelfRelation.apply(this, arguments);
}
inherits(Relation, BookshelfRelation);
Relation.prototype.Model = Model;
Relation.prototype.Collection = Collection;
// The `Model` constructor is referenced as a property on the `Bookshelf` instance,
// mixing in the correct `builder` method, as well as the `relation` method,
// passing in the correct `Model` & `Collection` constructors for later reference.
var ModelCtor = this.Model = SqlModel.extend({
_builder: function(tableName) {
return knex(tableName);
},
_relation: function(type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error('A valid target model must be defined for the ' +
_.result(this, 'tableName') + ' ' + type + ' relation');
}
return new Relation(type, Target, options);
Model.prototype._relation = function(type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error('A valid target model must be defined for the ' +
_.result(this, 'tableName') + ' ' + type + ' relation');
}
});
return new Relation(type, Target, options);
};
// Shortcut for creating a new collection with the current collection.
ModelCtor.collection = function(rows, options) {
return new CollectionCtor((rows || []), _.extend({}, options, {model: this}));
Model.collection = function(rows, options) {
return new Collection((rows || []), _.extend({}, options, {model: this}));
};
// The collection also references the correct `Model`, specified above, for creating
// new `Model` instances in the collection. We also extend with the correct builder /
// `knex` combo.
var CollectionCtor = this.Collection = SqlCollection.extend({
model: ModelCtor,
_builder: function(tableName) {
return knex(tableName);
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes in the
// `Events` object. It also contains the version number, and a `Transaction` method
// referencing the correct version of `knex` passed into the object.
_.extend(bookshelf, Events, Errors, {
// Helper method to wrap a series of Bookshelf actions in a `knex` transaction block;
transaction: function() {
return this.knex.transaction.apply(this, arguments);
},
// Provides a nice, tested, standardized way of adding plugins to a `Bookshelf` instance,
// injecting the current instance into the plugin, which should be a module.exports.
plugin: function(plugin, options) {
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
require(plugin)(this, options);
}
} else if (_.isArray(plugin)) {
_.each(plugin, function (plugin) {
this.plugin(plugin, options);
}, this);
} else {
plugin(this, options);
}
return this;
}
});
// Used internally, the `Relation` helps in simplifying the relationship building,
// centralizing all logic dealing with type & option handling.
var Relation = this.Relation = SqlRelation.extend({
Model: ModelCtor,
Collection: CollectionCtor
});

@@ -82,54 +132,29 @@

// for convenience.
this.knex = knex;
};
bookshelf.knex = knex;
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes in the
// `Events` object. It also contains the version number, and a `Transaction` method
// referencing the correct version of `knex` passed into the object.
_.extend(Bookshelf.prototype, Events, {
// The `forge` function properly instantiates a new Model or Collection
// without needing the `new` operator... to make object creation cleaner
// and more chainable.
Model.forge = Collection.forge = function() {
var inst = Object.create(this.prototype);
var obj = this.apply(inst, arguments);
return (Object(obj) === obj ? obj : inst);
};
// Keep in sync with `package.json`.
VERSION: '0.6.12',
// Attach `where`, `query`, and `fetchAll` as static methods.
['where', 'query'].forEach(function(method) {
Model[method] =
Collection[method] = function() {
var model = this.forge();
return model[method].apply(model, arguments);
};
});
Model.fetchAll = function(options) { return this.forge().fetchAll(options); };
// Helper method to wrap a series of Bookshelf actions in a `knex` transaction block;
transaction: function() {
return this.knex.transaction.apply(this, arguments);
},
Model.extend = Collection.extend = require('simple-extend');
// Provides a nice, tested, standardized way of adding plugins to a `Bookshelf` instance,
// injecting the current instance into the plugin, which should be a module.exports.
plugin: function(plugin, options) {
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
require(plugin)(this, options);
}
} else if (_.isArray(plugin)) {
_.each(plugin, function (plugin) {
this.plugin(plugin, options);
}, this);
} else {
plugin(this, options);
}
return this;
}
});
// Alias to `new Bookshelf(opts)`.
Bookshelf.initialize = function(knex) {
return new this(knex);
return bookshelf;
};
// The `forge` function properly instantiates a new Model or Collection
// without needing the `new` operator... to make object creation cleaner
// and more chainable.
SqlModel.forge = SqlCollection.forge = function() {
var inst = Object.create(this.prototype);
var obj = this.apply(inst, arguments);
return (Object(obj) === obj ? obj : inst);
};
// Finally, export `Bookshelf` to the world.
module.exports = Bookshelf;
module.exports = Bookshelf;
{
"name": "bookshelf",
"version": "0.6.12",
"description": "A lightweight ORM for PostgreSQL, MySQL, and SQLite3, influenced by Backbone.js",
"version": "0.7.0",
"description": "A lightweight ORM for PostgreSQL, MySQL, and SQLite3",
"main": "bookshelf.js",
"scripts": {
"test": "mocha -t 5000 --check-leaks -R spec test/index.js",
"doc": "groc -o docs --verbose dialects/base/collection.js dialects/**/*.js plugins/*.js bookshelf.js",
"release:patch": "git checkout master && export BOOKSHELF_DEV=0 && npm run-script test && npm run-script doc && git add . && git commit -m 'docs prep for release' && grunt release:patch",
"release:minor": "git checkout master && export BOOKSHELF_DEV=0 && npm run-script test && npm run-script doc && git add . && git commit -m 'docs prep for release' && grunt release:minor"
"jshint": "jshint bookshelf.js lib/*",
"test": "mocha -b -t 5000 --check-leaks -R spec test/index.js",
"release:patch": "npm run jshint && npm test && gulp build && gulp bump --type patch && gulp release",
"release:minor": "npm run jshint && npm test && gulp build && gulp bump --type minor && gulp release"
},

@@ -26,26 +26,35 @@ "homepage": "http://bookshelfjs.org",

"peerDependencies": {
"knex": "0.5.x"
"knex": "0.6.x"
},
"dependencies": {
"backbone": "1.1.0",
"inflection": "1.2.x",
"inflection": "~1.3.5",
"trigger-then": "0.3.x",
"bluebird": "1.2.x",
"lodash": ">=2.0.0"
"bluebird": "~2.0.5",
"lodash": ">=2.0.0",
"simple-extend": "0.1.0",
"inherits": "~2.0.1",
"semver": "~2.3.0",
"create-error": "~0.3.1"
},
"devDependencies": {
"mocha": "1.18.x",
"mysql": "~2.0.0-alpha7",
"pg": "~2.8.2",
"sqlite3": "~2.1.7",
"objectdump": "~0.3.0",
"minimist": "~0.0.9",
"through": "^2.3.4",
"browserify": "^4.0.0",
"gulp": "^3.6.2",
"gulp-bump": "^0.1.8",
"gulp-git": "^0.4.2",
"gulp-shell": "^0.2.5",
"knex": "0.6.x",
"mocha": "~1.20.1",
"mysql": "~2.3.2",
"pg": "~3.3.0",
"sqlite3": "~2.2.3",
"underscore.string": "~2.3.1",
"grunt": "~0.4.1",
"grunt-release": "~0.6.0",
"chai-as-promised": "~4.1.0",
"chai": "~1.8.0",
"sinon-chai": "~2.4.0",
"sinon": "~1.7.3",
"chai": "~1.9.1",
"sinon-chai": "~2.5.0",
"sinon": "~1.10.2",
"node-uuid": "~1.4.1",
"knex": "0.5.x"
"jshint": "~2.5.1"
},

@@ -52,0 +61,0 @@ "author": {

@@ -1,21 +0,49 @@

```
._. ._.
| | ______ _ _ _ __ | |
| | | ___ \ | | | | | |/ _| | |
| | | |_/ / ___ ___ | | _____| |__ ___| | |_ | |
| | | ___ \/ _ \ / _ \| |/ / __| '_ \ / _ \ | _| | |
| | | |_/ / (_) | (_) | <\__ \ | | | __/ | | | |
| | \____/ \___/ \___/|_|\_\___/_| |_|\___|_|_| | |
|----------------------------------------------------------|
\--------\ /----------------------------------\ /--------/
\/ \/
```
# [bookshelf.js](http://bookshelfjs.org) [![Build Status](https://travis-ci.org/tgriesser/bookshelf.png?branch=master)](https://travis-ci.org/tgriesser/bookshelf)
Bookshelf is a node.js ORM with support for postgreSQL, mySQL, and SQLite3.
It is built atop the <a href="http://knexjs.org">Knex Query Builder</a>,
Bookshelf is a Node.js ORM with support for PostgreSQL, MySQL / MariaDB, and SQLite3.
It is built atop the <a href="http://knexjs.org">Knex Query Builder</a>,
and is strongly influenced by the Model and Collection foundations of Backbone.js.
It features transaction support, one-to-one, one-to-many, and many-to-many relations.
It features [transaction support](http://bookshelfjs.org/#Bookshelf-transaction), one-to-one, one-to-many, many-to-many, and polymorphic relations.
For Docs, License, Tests, FAQ, and other information, see: http://bookshelfjs.org.
To suggest a feature, report a bug, or general discussion: http://github.com/tgriesser/bookshelf/issues/
To suggest a feature, report a bug, or general discussion: http://github.com/tgriesser/bookshelf/issues/
## Examples
We have several examples [on the website](http://bookshelfjs.org). Here is the first one to get you started:
```js
var knex = require('knex')({client: 'mysql', connection: process.env.MYSQL_DATABASE_CONNECTION });
var bookshelf = require('bookshelf')(knex);
var User = bookshelf.Model.extend({
tableName: 'users'
messages: function() {
return this.hasMany(Posts);
}
});
var Posts = bookshelf.Model.extend({
tableName: 'messages',
tags: function() {
return this.belongsToMany(Tag);
}
});
var Tag = bookshelf.Model.extend({
tableName: 'tags'
})
User.where('id', 1).fetch({withRelated: ['posts.tags']}).then(function(user) {
console.log(user.related('posts').toJSON());
}).catch(function(err) {
console.error(err);
});
```

@@ -13,4 +13,4 @@ var Promise = testPromise;

var CollectionBase = require(path.resolve(basePath + '/dialects/base/collection')).CollectionBase;
var ModelBase = require(path.resolve(basePath + '/dialects/base/model')).ModelBase;
var CollectionBase = require(path.resolve(basePath + '/lib/base/collection'));
var ModelBase = require(path.resolve(basePath + '/lib/base/model'));

@@ -17,0 +17,0 @@ describe('Collection', function() {

@@ -1,2 +0,2 @@

var Promise = require('../dialects/base/promise').Promise;
var Promise = require('../lib/base/promise');

@@ -9,3 +9,10 @@ Promise.longStackTraces();

global.testPromise = Promise;
var testQueryCache = global.testQueryCache = [];
var oldIt = it;
it = function() {
testQueryCache = [];
return oldIt.apply(this, arguments);
};
process.stderr.on('data', function(data) {

@@ -46,15 +53,3 @@ console.log(data);

describe('Integration Tests', function () {
var helper = require('./integration/helpers/logger');
before(function() {
helper.setLib(this);
});
require('./integration')(Bookshelf);
after(function() {
helper.writeResult();
});
});

@@ -9,3 +9,5 @@ var _ = require('lodash');

var MySQL = Bookshelf.initialize({
var pg = require('knex')({client: 'postgres', connection: config.postgres});
var sqlite3 = require('knex')({client: 'sqlite3', connection: config.sqlite3});
var mysql = require('knex')({
client: 'mysql',

@@ -22,29 +24,12 @@ connection: config.mysql,

var PostgreSQL = Bookshelf.initialize({
client: 'postgres',
connection: config.postgres,
});
var MySQL = require('bookshelf')(mysql);
var PostgreSQL = require('bookshelf')(pg);
var SQLite3 = require('bookshelf')(sqlite3);
var SQLite3 = Bookshelf.initialize({
client: 'sqlite3',
connection: config.sqlite3,
});
var knexSqlite3 = Knex.initialize({
client: 'sqlite3',
connection: config.sqlite3
});
it('should allow creating a Bookshelf client from a Knex instance', function() {
var bookshelf = Bookshelf.initialize(knexSqlite3);
expect(bookshelf.knex).to.equal(knexSqlite3);
});
it('should allow creating a new Bookshelf instance with "new"', function() {
var bookshelf = new Bookshelf(knexSqlite3);
expect(bookshelf.knex).to.equal(knexSqlite3);
var bookshelf = new Bookshelf(sqlite3);
expect(bookshelf.knex).to.equal(sqlite3);
});
_.each([MySQL, PostgreSQL, SQLite3], function(bookshelf) {
describe('Dialect: ' + bookshelf.knex.client.dialect, function() {

@@ -76,2 +61,2 @@

};
};
var Promise = global.testPromise;
module.exports = function(Bookshelf) {
module.exports = function(bookshelf) {

@@ -9,5 +9,15 @@ describe('Collection', function() {

var Models = require('./helpers/objects')(Bookshelf).Models;
var Collections = require('./helpers/objects')(Bookshelf).Collections;
var output = require('./output/Collection');
var dialect = bookshelf.knex.client.dialect;
var json = function(model) {
return JSON.parse(JSON.stringify(model));
};
var checkTest = function(ctx) {
return function(resp) {
expect(json(resp)).to.eql(output[ctx.test.title][dialect].result);
};
};
var Models = require('./helpers/objects')(bookshelf).Models;
// Models

@@ -26,17 +36,9 @@ var Site = Models.Site;

// Collections
var Sites = Collections.Sites;
var Admins = Collections.Admins;
var Blogs = Collections.Blogs;
var Posts = Collections.Posts;
var Comments = Collections.Comment;
var Photos = Collections.Photos;
describe('fetch', function() {
it ('fetches the models in a collection', function() {
return Bookshelf.Collection.extend({tableName: 'posts'})
return bookshelf.Collection.extend({tableName: 'posts'})
.forge()
.logMe()
.fetch();
.fetch()
.tap(checkTest(this));
});

@@ -83,4 +85,4 @@

it('creates a new instance of Sync', function(){
var model = new Bookshelf.Model();
expect(model.sync(model)).to.be.an.instanceOf(require('../../dialects/sql/sync').Sync);
var model = new bookshelf.Model();
expect(model.sync(model)).to.be.an.instanceOf(require('../../lib/sync'));
});

@@ -94,3 +96,3 @@

return new Sites().create({name: 'google.com'}).then(function(model) {
return Site.collection().create({name: 'google.com'}).then(function(model) {
expect(model.get('name')).to.equal('google.com');

@@ -143,8 +145,7 @@ return model.destroy();

var query = authors.query();
query.then = function(onFufilled, onRejected) {
expect(this.values[0]).to.eql([['first_name', 'Test'], ['last_name', 'User'], ['site_id', 1]]);
// TODO: Make this doable again...
// expect(this.values[0]).to.eql([['first_name', 'Test'], ['last_name', 'User'], ['site_id', 1]]);
return Promise.resolve(this.toString()).then(onFufilled, onRejected);
};
return authors.create({first_name: 'Test', last_name: 'User'});

@@ -156,3 +157,2 @@ });

return new Author({id: 1}).fetch({withRelated: 'site.photos'}).then(function(author) {
return author.related('site').related('photos').create({

@@ -171,2 +171,12 @@ imageable_id: author.related('site').id,

it('can require items in the response', function() {
return expect(bookshelf.Collection.extend({tableName: 'posts'})
.query('where', {id: '1000'})
.fetch({require: true})
.catch(function(err) {
expect(err.message).to.equal('EmptyError');
throw err;
}))
.to.be.rejectedWith(bookshelf.Collection.EmptyError);
});

@@ -173,0 +183,0 @@ });

@@ -22,145 +22,120 @@ var _ = require('lodash');

return Promise.all([
schema.createTable('sites', function(table) {
table.increments('id');
table.string('name');
}),
return schema.createTable('sites', function(table) {
table.increments('id');
table.string('name');
})
.createTable('sitesmeta', function(table) {
table.increments('id');
table.integer('site_id').notNullable();
table.text('description');
})
.createTable('info', function(table) {
table.increments('id');
table.integer('meta_id').notNullable();
table.text('other_description');
})
.createTable('admins', function(table) {
table.increments('id');
table.string('username');
table.string('password');
table.timestamps();
})
.createTable('admins_sites', function(table) {
table.increments('id');
table.integer('admin_id').notNullable();
table.integer('site_id').notNullable();
table.string('item').defaultTo('test');
})
.createTable('blogs', function(table) {
table.increments('id');
table.integer('site_id').notNullable();
table.string('name');
})
.createTable('authors', function(table) {
table.increments('id');
table.integer('site_id').notNullable();
table.string('first_name');
table.string('last_name');
})
.createTable('posts', function(table) {
table.increments('id');
table.integer('owner_id').notNullable();
table.integer('blog_id').notNullable();
table.string('name');
table.text('content');
})
.createTable('authors_posts', function(table) {
table.increments('id');
table.integer('author_id').notNullable();
table.integer('post_id').notNullable();
})
.createTable('tags', function(table) {
table.increments('id');
table.string('name');
})
.createTable('posts_tags', function(table) {
table.increments('id');
table.integer('post_id').notNullable();
table.integer('tag_id').notNullable();
})
.createTable('comments', function(table) {
table.increments('id');
table.integer('post_id').notNullable();
table.string('name');
table.string('email');
table.text('comment');
})
.createTable('users', function(table) {
table.increments('uid');
table.string('username');
})
.createTable('roles', function(table) {
table.increments('rid');
table.string('name');
})
.createTable('users_roles', function(table) {
table.integer('rid').notNullable();
table.integer('uid').notNullable();
})
.createTable('photos', function(table) {
table.increments('id');
table.string('url');
table.string('caption');
table.integer('imageable_id').notNullable();
table.string('imageable_type');
})
.createTable('Customer', function(table) {
table.increments('id');
table.string('name');
})
.createTable('Settings', function(table) {
table.increments('id');
table.integer('Customer_id').notNullable();
table.string('data', 64);
})
.createTable('hostnames', function(table){
table.string('hostname');
table.integer('instance_id').notNullable();
table.enu('route', ['annotate','submit']);
})
.createTable('instances', function(table){
table.bigIncrements('id');
table.string('name');
})
.createTable('uuid_test', function(table) {
table.uuid('uuid');
table.string('name');
})
.createTable('parsed_users', function(table) {
table.increments();
table.string('name');
})
.createTable('tokens', function(table) {
table.increments();
table.string('parsed_user_id');
table.string('token');
});
schema.createTable('sitesmeta', function(table) {
table.increments('id');
table.integer('site_id').notNullable();
table.text('description');
}),
schema.createTable('info', function(table) {
table.increments('id');
table.integer('meta_id').notNullable();
table.text('other_description');
}),
schema.createTable('admins', function(table) {
table.increments('id');
table.string('username');
table.string('password');
table.timestamps();
}),
schema.createTable('admins_sites', function(table) {
table.increments('id');
table.integer('admin_id').notNullable();
table.integer('site_id').notNullable();
table.string('item').defaultTo('test');
}),
schema.createTable('blogs', function(table) {
table.increments('id');
table.integer('site_id').notNullable();
table.string('name');
}),
schema.createTable('authors', function(table) {
table.increments('id');
table.integer('site_id').notNullable();
table.string('first_name');
table.string('last_name');
}),
schema.createTable('posts', function(table) {
table.increments('id');
table.integer('owner_id').notNullable();
table.integer('blog_id').notNullable();
table.string('name');
table.text('content');
}),
schema.createTable('authors_posts', function(table) {
table.increments('id');
table.integer('author_id').notNullable();
table.integer('post_id').notNullable();
}),
schema.createTable('tags', function(table) {
table.increments('id');
table.string('name');
}),
schema.createTable('posts_tags', function(table) {
table.increments('id');
table.integer('post_id').notNullable();
table.integer('tag_id').notNullable();
}),
schema.createTable('comments', function(table) {
table.increments('id');
table.integer('post_id').notNullable();
table.string('name');
table.string('email');
table.text('comment');
}),
schema.createTable('users', function(table) {
table.increments('uid');
table.string('username');
}),
schema.createTable('roles', function(table) {
table.increments('rid');
table.string('name');
}),
schema.createTable('users_roles', function(table) {
table.integer('rid').notNullable();
table.integer('uid').notNullable();
}),
schema.createTable('photos', function(table) {
table.increments('id');
table.string('url');
table.string('caption');
table.integer('imageable_id').notNullable();
table.string('imageable_type');
}),
schema.createTable('Customer', function(table) {
table.increments('id');
table.string('name');
}),
schema.createTable('Settings', function(table) {
table.increments('id');
table.integer('Customer_id').notNullable();
table.string('data', 64);
}),
schema.createTable('hostnames', function(table){
table.string('hostname');
table.integer('instance_id').notNullable();
table.enu('route', ['annotate','submit']);
}),
schema.createTable('instances', function(table){
table.bigIncrements('id');
table.string('name');
}),
schema.createTable('uuid_test', function(table) {
table.uuid('uuid');
table.string('name');
}),
schema.createTable('parsed_users', function(table) {
table.increments();
table.string('name');
}),
schema.createTable('tokens', function(table) {
table.increments();
table.string('parsed_user_id');
table.string('token');
})
]);
});
};

@@ -1,2 +0,1 @@

// All Models & Collections Used in the Tests

@@ -66,6 +65,2 @@ // (sort of mimics a simple multi-site blogging engine)

var Sites = Bookshelf.Collection.extend({
model: Site
});
var Admin = Bookshelf.Model.extend({

@@ -76,7 +71,2 @@ tableName: 'admins',

// All admins for a site.
var Admins = Bookshelf.Collection.extend({
model: Admin
});
// Author of a blog post.

@@ -107,6 +97,2 @@ var Author = Bookshelf.Model.extend({

var Authors = Bookshelf.Collection.extend({
model: Author
});
// A blog for a site.

@@ -131,10 +117,6 @@ var Blog = Bookshelf.Model.extend({

comments: function() {
return this.hasMany(Comments).through(Post);
return this.hasMany(Comment).through(Post);
}
});
var Blogs = Bookshelf.Collection.extend({
model: Blog
});
// An individual post on a blog.

@@ -187,6 +169,2 @@ var Post = Bookshelf.Model.extend({

var Comments = Bookshelf.Collection.extend({
model: Comment
});
var Tag = Bookshelf.Model.extend({

@@ -303,11 +281,2 @@ tableName: 'tags',

Uuid: Uuid
},
Collections: {
Sites: Sites,
Admins: Admins,
Posts: Posts,
Blogs: Blogs,
Comments: Comments,
Photos: Photos,
Authors: Authors
}

@@ -314,0 +283,0 @@ };

@@ -10,3 +10,3 @@ var _ = require('lodash');

module.exports = function(Bookshelf) {
module.exports = function(bookshelf) {

@@ -16,3 +16,3 @@ describe('Model', function() {

var Backbone = require('backbone');
var Models = require('./helpers/objects')(Bookshelf).Models;
var Models = require('./helpers/objects')(bookshelf).Models;

@@ -29,3 +29,3 @@ var stubSync = {

var User = Bookshelf.Model.extend({
var User = bookshelf.Model.extend({
idAttribute: 'user_id',

@@ -55,6 +55,6 @@ getData: function() { return 'test'; }

it('accepts a custom `constructor` property', function() {
var User = Bookshelf.Model.extend({
var User = bookshelf.Model.extend({
constructor: function() {
this.item = 'test';
Bookshelf.Model.apply(this, arguments);
bookshelf.Model.apply(this, arguments);
}

@@ -75,3 +75,3 @@ });

it('should create a new model instance', function() {
var User = Bookshelf.Model.extend({
var User = bookshelf.Model.extend({
tableName: 'users'

@@ -88,3 +88,3 @@ });

it('should attach the id as a property on the model', function() {
var test = new Bookshelf.Model({id: 1});
var test = new bookshelf.Model({id: 1});
equal(test.id, (1));

@@ -94,3 +94,3 @@ });

it('should reference idAttribute as the key for model.id', function() {
var Test = Bookshelf.Model.extend({
var Test = bookshelf.Model.extend({
idAttribute: '_id'

@@ -109,3 +109,3 @@ });

_.each(attached, function(item) {
deepEqual(Bookshelf.Model.prototype[item], Backbone.Model.prototype[item]);
deepEqual(bookshelf.Model.prototype[item], Backbone.Model.prototype[item]);
});

@@ -120,7 +120,7 @@ });

beforeEach(function() {
model = new Bookshelf.Model();
model = new bookshelf.Model();
});
it('returns the Knex builder when no arguments are passed', function() {
equal((model.query() instanceof require('knex/lib/builder').Builder), true);
equal((model.query() instanceof bookshelf.knex.client.QueryBuilder), true);
});

@@ -135,6 +135,6 @@

var qb = model.resetQuery().query();
equal(qb.wheres.length, 0);
equal(_.where(qb._statements, {grouping: 'where'}).length, 0);
var q = model.query('where', {id:1});
equal(q, (model));
equal(qb.wheres.length, 1);
equal(_.where(qb._statements, {grouping: 'where'}).length, 1);
});

@@ -144,6 +144,6 @@

var qb = model.resetQuery().query();
equal(qb.wheres.length, 0);
equal(_.where(qb._statements, {grouping: 'where'}).length, 0);
var q = model.query({where: {id: 1}, orWhere: ['id', '>', '10']});
equal(q, model);
equal(qb.wheres.length, 2);
equal(_.where(qb._statements, {grouping: 'where'}).length, 2);
});

@@ -153,3 +153,3 @@

var qb = model.resetQuery().query();
equal(qb.wheres.length, 0);
equal(_.where(qb._statements, {grouping: 'where'}).length, 0);
var q = model.query(function(qb) {

@@ -159,5 +159,5 @@ this.where({id: 1}).orWhere('id', '>', '10');

equal(q, model);
equal(qb.wheres.length, 2);
equal(_.where(qb._statements, {grouping: 'where'}).length, 2);
qb = model.resetQuery().query();
equal(qb.wheres.length, 0);
equal(_.where(qb._statements, {grouping: 'where'}).length, 0);
q = model.query(function(qb) {

@@ -167,3 +167,3 @@ qb.where({id: 1}).orWhere('id', '>', '10');

equal(q, model);
equal(qb.wheres.length, 2);
equal(_.where(qb._statements, {grouping: 'where'}).length, 2);
});

@@ -175,3 +175,3 @@

var table = new Bookshelf.Model({}, {tableName: 'customers'});
var table = new bookshelf.Model({}, {tableName: 'customers'});

@@ -183,3 +183,4 @@ it('can be passed in the initialize options', function() {

it('should set the tableName for the query builder', function() {
equal(table.query().from(), ('customers'));
// TODO: Make this doable again...
// equal(_.findWhere(table.query().statements, {grouping: 'table'}).value, '`customers`');
});

@@ -192,3 +193,3 @@

it('includes the idAttribute in the hash', function() {
var m = new (Bookshelf.Model.extend({
var m = new (bookshelf.Model.extend({
idAttribute: '_id'

@@ -200,4 +201,4 @@ }))({'_id': 1, 'name': 'Joe'});

it('includes the relations loaded on the model, unless {shallow: true} is passed.', function() {
var m = new Bookshelf.Model({id: 1, name: 'Test'});
m.relations = {someList: new Bookshelf.Collection([{id:1}, {id:2}])};
var m = new bookshelf.Model({id: 1, name: 'Test'});
m.relations = {someList: new bookshelf.Collection([{id:1}, {id:2}])};
var json = m.toJSON();

@@ -319,3 +320,3 @@ deepEqual(_.keys(json), ['id', 'name', 'someList']);

equal(m.get('id'), 4);
return new Bookshelf.Collection(null, {model: Site}).fetch();
return new bookshelf.Collection(null, {model: Site}).fetch();
})

@@ -332,3 +333,3 @@ .then(function(c) {

.then(function() {
return new Bookshelf.Collection(null, {model: Site}).fetch();
return new bookshelf.Collection(null, {model: Site}).fetch();
})

@@ -345,3 +346,3 @@ .then(function(c) {

.then(function() {
return new Bookshelf.Collection(null, {model: Site}).fetch();
return Site.fetchAll();
})

@@ -371,6 +372,6 @@ .then(function(c) {

var m = new Bookshelf.Model({id: null}).query({where: {uuid: 'testing'}});
var m = new bookshelf.Model({id: null}).query({where: {uuid: 'testing'}});
var query = m.query();
query.update = function() {
equal(this.wheres.length, 1);
equal(_.where(this._statements, {grouping: 'where'}).length, 1);
return Promise.resolve(1);

@@ -381,6 +382,7 @@ };

var m2 = new Bookshelf.Model({id: 1}).query({where: {uuid: 'testing'}});
var m2 = new bookshelf.Model({id: 1}).query({where: {uuid: 'testing'}});
var query2 = m2.query();
query2.update = function() {
equal(this.wheres.length, 2);
equal(_.where(this._statements, {grouping: 'where'}).length, 2);
return {};
};

@@ -396,8 +398,8 @@

var user = new Bookshelf.Model({id: 1, first_name: 'Testing'}, {tableName: 'users'});
var user = new bookshelf.Model({id: 1, first_name: 'Testing'}, {tableName: 'users'});
var query = user.query();
query.then = function(onFulfilled, onRejected) {
equal(this.bindings.length, 2);
equal(this.wheres.length, 1);
deepEqual(this._single.update, {bio: 'Short user bio'});
equal(_.where(this._statements, {grouping: 'where'}).length, 1);
return Promise.resolve(1).then(onFulfilled, onRejected);

@@ -417,3 +419,3 @@ };

it('fires saving and creating and then saves', function() {
var user = new Bookshelf.Model({first_name: 'Testing'}, {tableName: 'users'});
var user = new bookshelf.Model({first_name: 'Testing'}, {tableName: 'users'});
var query = user.query();

@@ -440,3 +442,3 @@ var events = 0;

it('rejects if the saving event throws an error', function() {
var Test = Bookshelf.Model.extend({
var Test = bookshelf.Model.extend({
tableName: 'test',

@@ -488,3 +490,3 @@ initialize: function() {

return new Site({id: 5}).destroy().then(function() {
return new Bookshelf.Collection(null, {model: Site}).fetch();
return new bookshelf.Collection(null, {model: Site}).fetch();
})

@@ -544,6 +546,6 @@ .then(function(c) {

it('deletes the `_builder` property, resetting the model query builder', function() {
var m = new Bookshelf.Model().query('where', {id: 1});
equal(m.query().wheres.length, 1);
var m = new bookshelf.Model().query('where', {id: 1});
equal(_.where(m.query()._statements, {grouping: 'where'}).length, 1);
m.resetQuery();
equal(m.query().wheres.length, 0);
equal(_.where(m.query()._statements, {grouping: 'where'}).length, 0);
});

@@ -555,3 +557,3 @@ });

it('will set the created_at and updated_at columns if true', function() {
var m = new (Bookshelf.Model.extend({hasTimestamps: true}))();
var m = new (bookshelf.Model.extend({hasTimestamps: true}))();
m.sync = function() {

@@ -567,3 +569,3 @@ equal(this.get('item'), 'test');

it('only sets the updated_at for existing models', function() {
var m1 = new (Bookshelf.Model.extend({hasTimestamps: true}))();
var m1 = new (bookshelf.Model.extend({hasTimestamps: true}))();
m1.sync = function() {

@@ -578,3 +580,3 @@ equal(this.get('item'), 'test');

it('allows passing hasTimestamps in the options hash', function() {
var m = new Bookshelf.Model(null, {hasTimestamps: true});
var m = new bookshelf.Model(null, {hasTimestamps: true});
m.sync = function() {

@@ -590,3 +592,3 @@ equal(this.get('item'), 'test');

it('allows custom keys for the created at & update at values', function() {
var m = new Bookshelf.Model(null, {hasTimestamps: ['createdAt', 'updatedAt']});
var m = new bookshelf.Model(null, {hasTimestamps: ['createdAt', 'updatedAt']});
m.sync = function() {

@@ -602,3 +604,3 @@ equal(this.get('item'), 'test');

it('does not set created_at when {method: "update"} is passed', function() {
var m = new Bookshelf.Model(null, {hasTimestamps: true});
var m = new bookshelf.Model(null, {hasTimestamps: true});
m.sync = function() {

@@ -614,3 +616,3 @@ equal(this.get('item'), 'test');

it('will accept a falsy value as an option for created and ignore it', function() {
var m = new Bookshelf.Model(null, {hasTimestamps: ['createdAt', null]});
var m = new bookshelf.Model(null, {hasTimestamps: ['createdAt', null]});
m.sync = function() {

@@ -626,3 +628,3 @@ equal(this.get('item'), 'test');

it('will accept a falsy value as an option for updated and ignore it', function() {
var m = new Bookshelf.Model(null, {hasTimestamps: [null, 'updatedAt']});
var m = new bookshelf.Model(null, {hasTimestamps: [null, 'updatedAt']});
m.sync = function() {

@@ -642,4 +644,4 @@ equal(this.get('item'), 'test');

it('will set the `updated_at` attribute to a date, and the `created_at` for new entries', function() {
var m = new Bookshelf.Model();
var m1 = new Bookshelf.Model({id: 1});
var m = new bookshelf.Model();
var m1 = new bookshelf.Model({id: 1});
var ts = m.timestamp();

@@ -654,16 +656,6 @@ var ts2 = m1.timestamp();

describe('resetQuery', function() {
it('deletes the `_builder` property, resetting the model query builder', function() {
var m = new Bookshelf.Model().query('where', {id: 1});
equal(m.query().wheres.length, 1);
m.resetQuery();
equal(m.query().wheres.length, 0);
});
});
describe('defaults', function() {
it('assigns defaults on save, rather than initialize', function() {
var Item = Bookshelf.Model.extend({defaults: {item: 'test'}});
var Item = bookshelf.Model.extend({defaults: {item: 'test'}});
var item = new Item({newItem: 'test2'});

@@ -679,3 +671,3 @@ deepEqual(item.toJSON(), {newItem: 'test2'});

it('only assigns defaults when creating a model, unless {defaults: true} is passed in the save options', function() {
var Item = Bookshelf.Model.extend({defaults: {item: 'test'}});
var Item = bookshelf.Model.extend({defaults: {item: 'test'}});
var item = new Item({id: 1, newItem: 'test2'});

@@ -701,4 +693,4 @@ deepEqual(item.toJSON(), {id: 1, newItem: 'test2'});

it('creates a new instance of Sync', function(){
var model = new Bookshelf.Model();
equal((model.sync(model) instanceof require('../../dialects/sql/sync').Sync), true);
var model = new bookshelf.Model();
equal((model.sync(model) instanceof require('../../lib/sync')), true);
});

@@ -710,3 +702,3 @@ });

it('uses the idAttribute to determine if the model isNew', function(){
var model = new Bookshelf.Model();
var model = new bookshelf.Model();
model.id = 1;

@@ -762,8 +754,8 @@ equal(model.isNew(), false);

it('creates a new collection for the current model', function() {
expect(Bookshelf.Model.collection()).to.be.an.instanceOf(Bookshelf.Collection);
expect(bookshelf.Model.collection()).to.be.an.instanceOf(bookshelf.Collection);
var NewModel = Bookshelf.Model.extend({test: 1});
var NewModel = bookshelf.Model.extend({test: 1});
var newModelCollection = NewModel.collection([{id: 1}]);
expect(newModelCollection).to.be.an.instanceOf(Bookshelf.Collection);
expect(newModelCollection).to.be.an.instanceOf(bookshelf.Collection);
expect(newModelCollection.at(0)).to.be.an.instanceOf(NewModel);

@@ -770,0 +762,0 @@ });

@@ -7,3 +7,3 @@ var equal = require('assert').equal;

var Relation = require('../../dialects/sql/relation').Relation;
var Relation = require('../../lib/relation');

@@ -10,0 +10,0 @@ var Photo = Bookshelf.Model.extend({

@@ -9,6 +9,16 @@ var _ = require('lodash');

var output = require('./output/Relations');
var dialect = Bookshelf.knex.client.dialect;
var json = function(model) {
return JSON.parse(JSON.stringify(model));
};
var checkTest = function(ctx) {
return function(resp) {
expect(json(resp)).to.eql(output[ctx.test.title][dialect].result);
};
};
var objs = require('./helpers/objects')(Bookshelf);
var Relation = objs.Relation;
var Models = objs.Models;
var Collections = objs.Collections;

@@ -34,11 +44,2 @@ // Models

// Collections
var Sites = Collections.Sites;
var Admins = Collections.Admins;
var Blogs = Collections.Blogs;
var Posts = Collections.Posts;
var Comments = Collections.Comments;
var Photos = Collections.Photos;
var Authors = Collections.Authors;
describe('Bookshelf Relations', function() {

@@ -52,4 +53,4 @@

.then(function(model) {
return model.site().fetch({log: true});
});
return model.site().fetch();
}).then(checkTest(this));
});

@@ -61,4 +62,5 @@

.then(function(model) {
return model.posts().fetch({log: true});
});
return model.posts().fetch();
})
.then(checkTest(this));
});

@@ -69,3 +71,4 @@

.meta()
.fetch({log: true});
.fetch()
.then(checkTest(this));
});

@@ -76,3 +79,4 @@

.posts()
.fetch({log: true});
.fetch()
.then(checkTest(this));
});

@@ -86,5 +90,4 @@

return new Site({id: 1}).fetch({
log: true,
withRelated: ['meta']
});
}).then(checkTest(this));
});

@@ -94,5 +97,4 @@

return new Site({id: 1}).fetch({
log: true,
withRelated: ['authors', 'blogs']
});
}).then(checkTest(this));
});

@@ -102,5 +104,4 @@

return new Blog({id: 3}).fetch({
log: true,
withRelated: ['site']
});
}).then(checkTest(this));
});

@@ -114,5 +115,4 @@

return new Post({id: 1}).fetch({
log: true,
withRelated: ['tags']
});
}).then(checkTest(this));
});

@@ -122,5 +122,4 @@

return new Site({id: 3}).fetch({
log: true,
withRelated: ['meta', 'blogs', 'authors.posts']
});
}).then(checkTest(this));
});

@@ -133,13 +132,11 @@

it('eager loads "hasOne" models correctly (sites -> meta)', function() {
return new Sites().fetch({
log: true,
return Site.fetchAll({
withRelated: ['meta']
});
}).then(checkTest(this));
});
it('eager loads "belongsTo" models correctly (blogs -> site)', function() {
return new Blogs().fetch({
log: true,
return Blog.fetchAll({
withRelated: ['site']
});
}).then(checkTest(this));
});

@@ -149,14 +146,9 @@

return new Site({id: 1}).fetch({
log: true,
withRelated: ['blogs']
});
}).then(checkTest(this));
});
it('eager loads "belongsToMany" models correctly (posts -> tags)', function() {
return new Posts()
.query('where', 'blog_id', '=', 1)
.fetch({
log: true,
withRelated: ['tags']
});
return Post.where('blog_id', 1).fetchAll({withRelated: ['tags']})
.then(checkTest(this));
});

@@ -170,5 +162,4 @@

return new Site({id: 1}).fetch({
log: true,
withRelated: ['authors.ownPosts']
});
}).then(checkTest(this));
});

@@ -178,5 +169,4 @@

return new Site({id: 1}).fetch({
log: true,
withRelated: ['authors.posts']
});
}).then(checkTest(this));
});

@@ -186,5 +176,4 @@

return new Site({id: 1}).fetch({
log: true,
withRelated: ['authors.ownPosts', 'authors.site', 'blogs.posts']
});
}).then(checkTest(this));
});

@@ -197,6 +186,5 @@

it('eager loads "hasMany" -> "hasMany" (sites -> authors.ownPosts)', function() {
return new Sites().fetch({
log: true,
return Site.fetchAll({
withRelated: ['authors.ownPosts']
});
}).then(checkTest(this));
});

@@ -209,3 +197,3 @@

it('eager loads relations on a populated model (site -> blogs, authors.site)', function() {
return new Site({id: 1}).fetch({log: true}).then(function(m) {
return new Site({id: 1}).fetch().tap(checkTest(this)).then(function(m) {
return m.load(['blogs', 'authors.site']);

@@ -216,3 +204,3 @@ });

it('eager loads attributes on a collection (sites -> blogs, authors.site)', function() {
return new Sites().fetch({log: true}).then(function(c) {
return Site.fetchAll().tap(checkTest(this)).then(function(c) {
return c.load(['blogs', 'authors.site']);

@@ -416,3 +404,4 @@ });

.roles()
.fetch({log: true});
.fetch()
.tap(checkTest(this));
});

@@ -422,3 +411,4 @@

return new User({uid: 1})
.fetch({log: true, withRelated: ['roles']});
.fetch({withRelated: ['roles']})
.tap(checkTest(this));
});

@@ -433,3 +423,4 @@

.photo()
.fetch({log: true});
.fetch()
.tap(checkTest(this));
});

@@ -440,3 +431,3 @@

.photos()
.fetch({log: true});
.fetch().tap(checkTest(this));
});

@@ -447,3 +438,3 @@

.imageable()
.fetch({log: true});
.fetch().tap(checkTest(this));
});

@@ -454,15 +445,15 @@

.imageable()
.fetch({log: true});
.fetch().tap(checkTest(this));
});
it('eager loads morphMany (sites -> photos)', function() {
return new Sites().fetch({log: true, withRelated: ['photos']});
return new Site().fetchAll({withRelated: ['photos']}).tap(checkTest(this));
});
it('eager loads morphTo (photos -> imageable)', function() {
return new Photos().fetch({log: true, withRelated: ['imageable']});
return Photo.fetchAll({withRelated: ['imageable']}).tap(checkTest(this));
});
it('eager loads beyond the morphTo, where possible', function() {
return new Photos().fetch({log: true, withRelated: ['imageable.authors']});
return Photo.fetchAll({withRelated: ['imageable.authors']}).tap(checkTest(this));
});

@@ -475,29 +466,31 @@

it('handles hasMany `through`', function() {
return new Blog({id: 1}).comments().fetch({log: true});
return new Blog({id: 1}).comments().fetch().tap(checkTest(this));
});
it('eager loads hasMany `through`', function() {
return new Blogs().query({where: {site_id: 1}}).fetch({
log: true,
return Blog.where({site_id: 1}).fetchAll({
withRelated: 'comments'
});
}).then(checkTest(this));
});
it('eager loads hasMany `through` using where / fetchAll', function() {
return Blog.where('site_id', 1).fetchAll({withRelated: 'comments'}).then(checkTest(this));
});
it('handles hasOne `through`', function() {
return new Site({id: 1}).info().fetch({log: true});
return new Site({id: 1}).info().fetch().tap(checkTest(this));
});
it('eager loads hasOne `through`', function() {
return new Sites().query('where', 'id', '<', 3).fetch({
log: true,
return Site.where('id', '<', 3).fetchAll({
withRelated: 'info'
});
}).then(checkTest(this));
});
it('eager loads belongsToMany `through`', function() {
return new Authors().fetch({log: true, withRelated: 'blogs'});
return Author.fetchAll({withRelated: 'blogs'}).tap(checkTest(this));
});
it('eager loads belongsTo `through`', function() {
return new Comments().fetch({log: true, withRelated: 'blog'});
return new Comment().fetchAll({withRelated: 'blog'}).tap(checkTest(this));
});

@@ -556,3 +549,3 @@

return new Hostname({hostname: 'google.com'}).fetch({log: true, withRelated: 'instance'});
return new Hostname({hostname: 'google.com'}).fetch({withRelated: 'instance'}).tap(checkTest(this));

@@ -563,3 +556,3 @@ });

return new Bookshelf.Collection([], {model: Hostname}).fetch({log: true, withRelated: 'instance'});
return new Bookshelf.Collection([], {model: Hostname}).fetch({ withRelated: 'instance'}).tap(checkTest(this));

@@ -634,3 +627,3 @@ });

it('parses eager-loaded morphTo relations (model)', function () {
return new Photos().fetch({ withRelated: 'imageableParsed.meta', log: true })
return Photo.fetchAll({ withRelated: 'imageableParsed.meta', log: true })
.then(function (photos) {

@@ -637,0 +630,0 @@ photos.forEach(function(photo) {

@@ -13,3 +13,3 @@ var Promise = testPromise;

var Model = require(path.resolve(basePath + '/dialects/sql/model')).Model;
var Model = require(path.resolve(basePath + '/lib/model'));

@@ -16,0 +16,0 @@ describe('SQL Model', function () {

@@ -11,3 +11,3 @@ var Promise = testPromise;

var Sync = require(path.resolve(basePath + '/dialects/sql/sync')).Sync;
var Sync = require(path.resolve(basePath + '/lib/sync'));

@@ -14,0 +14,0 @@ describe('Sync', function() {

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc