示例#1
0
module.exports = function(Bookshelf) {

  var Knex     = require('knex');
  var config   = require(process.env.BOOKSHELF_TEST || './integration/helpers/config');
  var Promise  = global.testPromise;

  var pg = require('knex')({client: 'postgres', connection: config.postgres});
  var sqlite3 = require('knex')({client: 'sqlite3', connection: config.sqlite3});
  var mysql = require('knex')({
    client: 'mysql',
    connection: config.mysql,
    pool: {
      afterCreate: function(connection, callback) {
        return Promise.promisify(connection.query, connection)("SET sql_mode='TRADITIONAL';", []).then(function() {
          callback(null, connection);
        });
      }
    }
  });

  var MySQL = require('../bookshelf')(mysql);
  var PostgreSQL = require('../bookshelf')(pg);
  var SQLite3 = require('../bookshelf')(sqlite3);
  var Swapped = require('../bookshelf')(Knex({}));
  Swapped.knex = sqlite3;

  it('should allow creating a new Bookshelf instance with "new"', function() {
    var bookshelf = new Bookshelf(sqlite3);
    expect(bookshelf.knex).to.equal(sqlite3);
  });

  it('should allow swapping in another knex instance', function() {
    var bookshelf = new Bookshelf(Knex({}));
    var Models = require('./integration/helpers/objects')(bookshelf).Models;
    var site = new Models.Site();

    return require('./integration/helpers/migration')(SQLite3).then(function() {
      return site.save()
        .then(function() {
          expect(false).to.equal(true);
        })
        .catch(function() {
          bookshelf.knex = sqlite3;
          return site.save();
        });
    });
  });

  _.each([MySQL, PostgreSQL, SQLite3, Swapped], function(bookshelf) {

    var dialect = bookshelf.knex.client.dialect;

    describe('Dialect: ' + dialect, function() {

      this.dialect = dialect;

      before(function() {
        return require('./integration/helpers/migration')(bookshelf).then(function() {
           return require('./integration/helpers/inserts')(bookshelf);
        });
      });

      // Only testing this against mysql for now, just so the toString is reliable...
      if (dialect === 'mysql') {
        require('./integration/relation')(bookshelf);
      } else if (dialect === 'postgresql') {
        require('./integration/json')(bookshelf);
      }

      require('./integration/model')(bookshelf);
      require('./integration/collection')(bookshelf);
      require('./integration/relations')(bookshelf);
      require('./integration/plugin')(bookshelf);
      require('./integration/plugins/virtuals')(bookshelf);
      require('./integration/plugins/visibility')(bookshelf);
      require('./integration/plugins/registry')(bookshelf);
      require('./integration/plugins/pagination')(bookshelf);
    });

  });

};
示例#2
0
import knex from 'knex';
import bookshelf from 'bookshelf';

import config from './config.json';

const k = knex(config);
const b = bookshelf(k);

export default b;
示例#3
0
'use strict'
var test = require('tape')
var Storage = require('./storage')
var knex = require('knex')
var dbPath = './test.sqlite'
var knexConnection = knex({client: 'sqlite3', connection: {filename: dbPath}, useNullAsDefault: true})
var storageOpts = {connection: knexConnection, context: 'foo'}
deleteDatabase()

test.onFinish(function () {
  knexConnection.destroy()
  deleteDatabase()
})

test('constructor', function (t) {
  t.plan(5)

  t.test('needs a context and knex connection', function (t) {
    t.plan(3)
    t.throws(() => new Storage())
    t.throws(() => new Storage({context: undefined}), /The option 'options.connection' is required./)
    t.doesNotThrow(() => new Storage({context: 'foo', connection: knexConnection}))
  })

  t.test('sets a default context', function (t) {
    t.plan(1)
    var storage = new Storage({connection: knexConnection})
    t.equal(storage.context, 'default')
  })

  t.test('allows a custom context', function (t) {
示例#4
0
 before('Initialize bookshelf', () => {
     bookshelf = bookshelfInit(knex({ client: 'pg' }));
 });
示例#5
0
var express = require('express');
var router = express.Router();
var Knex = require('knex')
var config = require('../knexfile')
var knex = Knex(config[process.env.NODE_ENV || 'development'])
var db = require('../lib/db')(knex)

/* GET home page. */
//-------DONE-------------//
 router.get('/', function(req, res, next) {
  db.getAll('houses', function(err, data) {
    res.render('houseindex', { Houses: data });
  })
});

 //   Houses routes
//DONE----------HOUSE By ID--------------//
router.get('/house/:id', function(req, res, next) {
  db.findOne('houses', req.params, function(err, data){
    db.findAllInHouse('characters', req.params.id, function(err, characters){
      res.render('houseview', { House: [data], People: characters });
    })
  })
});

router.get('/newhouse', function(req, res, next) {
  res.render('newHouse', { title: 'A New Dev' });
});

router.post('/newhouse', function(req, res, next) {
  db.addNew('houses', req.body, function(err, data){
describe('Accounts', () => {
  const knex = initKnex(knexConfig);
  let accounts;
  before((done) => {
    accounts = new Accounts({}, knex);
    knexCleaner.clean(knex, { mode: 'delete' }).then(() => {
      done();
    });
  });
  after((done) => {
    knexCleaner.clean(knex, { mode: 'delete' }).then(() => {
      done();
    });
  });
  describe('createUser', () => {
    it('creates a user', done => {
      accounts.createUser({
        username: '******',
        email: '*****@*****.**',
        provider: 'local',
        profile: 'profile',
      }).then(accountId => {
        expect(accountId).to.equal(1);
        Promise.all([
          accounts.knex('account-providers')
            .first('provider', 'identifier', 'profile')
            .where({ accountId })
            .then(result => {
              expect(result.provider).to.equal('local');
              expect(result.profile).to.equal(JSON.stringify('profile'));
            }),
          accounts.knex('account-emails')
            .first('email')
            .where({ accountId })
            .then(result => {
              expect(result.email).to.equal('*****@*****.**');
            }),
        ]).then(() => done());
      });
    });
    it('requires unique usernames', done => {
      accounts.createUser({
        username: '******',
        email: '*****@*****.**',
        provider: 'local',
        profile: 'profile',
      }).catch(err => {
        expect(err).to.be.ok;
        done();
      });
    });
    it('requires unique emails', done => {
      accounts.createUser({
        username: '******',
        email: '*****@*****.**',
        provider: 'local',
        profile: 'profile',
      }).catch(err => {
        expect(err).to.be.ok;
        done();
      });
    });
  });
  describe('findByUsername', () => {
    it('finds user id', done => {
      accounts.findByUsername('user1').then(id => {
        expect(id).to.equal(1);
        done();
      });
    });
    it('does not find a user id', done => {
      accounts.findByUsername('user2').then((id) => {
        expect(id).to.be.undefined;
        done();
      });
    });
  });
  describe('findByEmail', () => {
    it('finds user id', done => {
      accounts.findByEmail('*****@*****.**').then(id => {
        expect(id).to.equal(1);
        done();
      });
    });
    it('does not find a user id', done => {
      accounts.findByEmail('*****@*****.**').then((id) => {
        expect(id).to.be.undefined;
        done();
      });
    });
  });
  describe('findByProvider', () => {
    it('finds account id given a provider', done => {
      accounts.findByProvider('local', '1').then(accountId => {
        expect(accountId).to.be.equal(1);
        done();
      });
    });
    it('does not find an account id given a provider which does not exist', done => {
      accounts.findByProvider('local', '2').then(accountId => {
        expect(accountId).to.be.undefined;
        done();
      });
    });
  });
  describe('findHashById', () => {
    it('finds hash given user id', (done) => {
      accounts.registerUser({
        username: '******',
        password: '******',
      }).then(id => {
        accounts.findHashById(id)
          .then((hash) => {
            expect(hash).to.be.a.string;
            done();
          });
      });
    });
    it('does not find a hash given a user which does not exist', (done) => {
      accounts.findHashById(123)
          .then((hash) => {
            expect(hash).to.be.undefined;
            done();
          });
    });
  });
});
示例#7
0
import diehard from 'diehard'
import knex from 'knex'
import bookshelf from 'bookshelf'
import knexConfiguration from './knex'

const verbose = require('debug')('ha:db:bookshelf:verbose')

const repository = bookshelf(knex(knexConfiguration))

repository.plugin('visibility')

diehard.register(done => {
  verbose('Shutting down postgres connection.')
  repository.knex.destroy(() => {
    verbose('Postgres connection shutdown successfully.')
    done()
  })
})

export default repository
示例#8
0
"use strict";
var knexLib = require("knex");
var config_1 = require("../../config");
exports.knex = knexLib(config_1.dbConfig);
示例#9
0
var knex = require('knex');

var settings = require('./settings');

exports.pg = knex({
  client: 'pg',
  pool: { min: settings.psqlPoolMin, max: settings.psqlPoolMax },
  connection: settings.psqlConnectionString
});
export default function () {
    db = db || knex(knexConfig[node_env]);
    return db;
}
示例#11
0
import { Model } from 'objection';
import Knex from 'knex';
import config from '../config';

const knex = Knex({
    client: 'mysql2',
    connection: {
        host:     config('db.host'),
        database: config('db.name'),
        user:     config('db.user'),
        password: config('db.pass'),
        charset:  'utf8mb4'
    }
});

Model.knex(knex);
  development: {
     client: 'sqlite3',
     connection: {
       filename: __dirname + '/../../datastore/tandp.sqlite3'

     },
     useNullAsDefault: true
   },
   directory: __dirname + '/../../migrations-test',
   tableName: 'migrations'

}

// console.log(config)
var Knex = require('knex')
var knex = Knex(config.development)

// uses the data from the seed database
// before - run the mirgration script
// after - drop the tables

describe('get requests', () => {

  before( function (done) {
    knex.migrate.rollback(config)
     .then(function () {
       return knex.migrate.latest()
        .then(function() {
          return knex.seed.run();
        })
        .then(function() {
示例#13
0
文件: index.js 项目: garbin/koapi
 config (db = null) {
   if (!internal.config) {
     internal.config = db || process.env.KOAPI_DB_CONFIG
   }
   return internal.config
 },
 connect (knexConfig) {
   if (!internal.connection) {
     if (knexConfig instanceof knex.constructor) {
       internal.connection = knexConfig
     } else {
       const config = module.exports.config(knexConfig)
       if (!config) {
         throw new Error('You should call config before')
       }
       internal.connection = knex(config)
     }
   }
   if (!internal.bookshelf) {
     internal.bookshelf = Bookshelf(internal.connection)
     .plugin('registry')
     .plugin('virtuals')
     .plugin('visibility')
     .plugin('pagination')
     .plugin(modelBase.pluggable)
     .plugin(cascadeDelete)
     .plugin(softDelete)
     .plugin(mask)
     .plugin(uuid)
     .plugin(validate)
     .plugin(formatter)
'use strict';
var config = require('../config');
var knex = require('knex');

var db = knex({
  client: 'sqlite3',
  connection: {
    filename: `${config.baseDir}/${config.db}`
  },
  debug: false,
  useNullAsDefault: true
});

module.exports = db;
示例#15
0
 builder: function(table) {
   return Knex(table);
 },
示例#16
0
var Knex = require('knex');
var config = require('./../../knexfile.js');
var knex = Knex(config.dev);
module.exports = knex;
示例#17
0
import knex from 'knex'
import config from './config'


let opts = config.postgresConnection

export default knex({
    client: 'pg',
    connection: `postgres://${opts.username}:${opts.passwd}@${opts.hostname}:${opts.port}/${opts.dbname}`
})
示例#18
0
'use strict';

var Bookshelf = require('bookshelf');
var knex      = require('knex');

module.exports = Bookshelf
  .initialize(knex({
    client: 'pg'
  }))
  .plugin(require('../../src'));
示例#19
0
import bookshelfFactory from 'bookshelf'
import knexFactory from 'knex'

const knex = knexFactory({
  client: 'pg',
  connection: {
    port: process.env.DATABASE_PORT,
    host: process.env.DATABASE_HOST,
    user: process.env.DATABASE_USER,
    password: process.env.DATABASE_ACCESS_KEY,
    database: process.env.DATABASE_NAME
  }
})

const bookshelf = bookshelfFactory(knex)
bookshelf.plugin('registry')
bookshelf.plugin('virtuals')

export default bookshelf
示例#20
0
var express = require('express'),
	knex = require('knex'),
	bookshelf = require('bookshelf'),
	app = express();

// database setup
var db_config = knex(require('./knexfile').development);
var bookshelf = bookshelf(db_config);
app.set('bookshelf', bookshelf);

var User = bookshelf.Model.extend({
	tableName: 'users'
});

app.get('/new', function(req,res){
	var user = new User({email: '*****@*****.**'});
	user.save().then(function(){res.send(user); });
});

app.get('/', function(req, res){
	User.fetchAll().then(function(data){ res.send(data); });
});

var server = app.listen(3000, function(){
	console.log('listening on port %d', server.address().port);
});
示例#21
0
'use strict';

const Promise = require('bluebird');
const types = require('punchcard-content-types');
const config = require('config');

const tables = require('./database/tables');
const schemas = require('./database/schemas');
const utils = require('./utils');

const knex = require('knex');

const database = knex(config.knex);

/**
 * Initialize the database with provided schemas
 *
 * @returns {promise} - Configured knex object for use with the database
 */
const init = () => {
  return types(null, config).then(cts => {
    // Get Content Type fields
    const contentSchema = utils.singleItem('name', 'content', schemas).fields;

    // Filter out Content from Schemas
    const schemata = schemas.filter(schema => {
      if (schema.name === 'content') {
        return false;
      }

      return true;
示例#22
0
文件: db.js 项目: gitter-badger/slash
var config = require('config');
var knex = require('knex');

if(!global.db){
	global.db = knex(config.dbConfig);
}

module.exports = global.db;
		
示例#23
0
文件: db.js 项目: Cawerit/forms
var knex = require('knex');

// Load the file containing the connection configuration.
// NOTE: For security reasons, this file is not included in the source control.
// Request the file from the author of this project and drop it in folder "credentials" to get access to db.
var config = require('./credentials/rds.credentials.json');

module.exports = knex({
	client: 'mysql',
	connection: config,
	pool: {
		min: 0
	}
});
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs')
var port = process.env.PORT || 5000;
var hbs = require('handlebars');
var scrapeParagraphs = require('./scrapeParagraphs')

var env = process.env.NODE_ENV || 'development' // string
var knexConfig = require('./knexfile'); //big object
var knexGenerator = require('knex')
var knexDbConfig = knexConfig[env] //small object
global.knex = knexGenerator(knexDbConfig)

var scraper = require('./scraper.js')
var scrapeParagraphs = require('./scrapeParagraphs')

var app = express();
app.use(express.static('public'));
var hbs = require('express-hbs');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))

// Use `.hbs` for extensions and find partials in `views/partials`.
app.engine('hbs', hbs.express4({
  partialsDir: __dirname + '/views'
}));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
示例#25
0
var config = {  
  database: {
    dialect:  'sqlite3',
    connection: {
      filename: './dev.sqlite3'
    },
    useNullAsDefault: true
  },

  // the directory your migration files are located in
  directory: __dirname + '/migrations',

  // this table will be populated with some information about your
  // migration files.  it will be automatically created, if it
  // doesn't already exist.
  tableName: 'migrations'
}

var Knex = require('knex')
var knex = Knex(config.database)

module.exports = {
  knex: knex,
  config: config
}
示例#26
0
文件: index.js 项目: AaronLaw/Ghost
ConfigManager.prototype.set = function (config) {
    var localPath = '',
        contentPath,
        subdir;

    // Merge passed in config object onto our existing config object.
    // We're using merge here as it doesn't assign `undefined` properties
    // onto our cached config object.  This allows us to only update our
    // local copy with properties that have been explicitly set.
    _.merge(this._config, config);

    // Protect against accessing a non-existant object.
    // This ensures there's always at least a paths object
    // because it's referenced in multiple places.
    this._config.paths = this._config.paths || {};

    // Parse local path location
    if (this._config.url) {
        localPath = url.parse(this._config.url).path;
        // Remove trailing slash
        if (localPath !== '/') {
            localPath = localPath.replace(/\/$/, '');
        }
    }

    subdir = localPath === '/' ? '' : localPath;

    // Allow contentPath to be over-written by passed in config object
    // Otherwise default to default content path location
    contentPath = this._config.paths.contentPath || path.resolve(appRoot, 'content');

    if (!knexInstance && this._config.database && this._config.database.client) {
        knexInstance = knex(this._config.database);
    }

    _.merge(this._config, {
        database: {
            knex: knexInstance
        },
        paths: {
            'appRoot':          appRoot,
            'subdir':           subdir,
            'config':           this._config.paths.config || path.join(appRoot, 'config.js'),
            'configExample':    path.join(appRoot, 'config.example.js'),
            'corePath':         corePath,

            'contentPath':      contentPath,
            'themePath':        path.resolve(contentPath, 'themes'),
            'appPath':          path.resolve(contentPath, 'apps'),
            'imagesPath':       path.resolve(contentPath, 'images'),
            'imagesRelPath':    'content/images',

            'adminViews':       path.join(corePath, '/server/views/'),
            'helperTemplates':  path.join(corePath, '/server/helpers/tpl/'),
            'exportPath':       path.join(corePath, '/server/data/export/'),
            'lang':             path.join(corePath, '/shared/lang/'),
            'debugPath':        subdir + '/ghost/debug/',

            'availableThemes':  this._config.paths.availableThemes || {},
            'availableApps':    this._config.paths.availableApps || {},
            'builtScriptPath':  path.join(corePath, 'built/scripts/')
        }
    });

    // Also pass config object to
    // configUrl object to maintain
    // clean depedency tree
    configUrl.setConfig(this._config);

    // For now we're going to copy the current state of this._config
    // so it's directly accessible on the instance.
    // @TODO: perhaps not do this?  Put access of the config object behind
    // a function?
    _.extend(this, this._config);
};
示例#27
0
ConfigManager.prototype.set = function (config) {
    var localPath = '',
        contentPath,
        subdir,
        assetHash;

    // Merge passed in config object onto our existing config object.
    // We're using merge here as it doesn't assign `undefined` properties
    // onto our cached config object.  This allows us to only update our
    // local copy with properties that have been explicitly set.
    _.merge(this._config, config);

    // Protect against accessing a non-existant object.
    // This ensures there's always at least a paths object
    // because it's referenced in multiple places.
    this._config.paths = this._config.paths || {};

    // Parse local path location
    if (this._config.url) {
        localPath = url.parse(this._config.url).path;
        // Remove trailing slash
        if (localPath !== '/') {
            localPath = localPath.replace(/\/$/, '');
        }
    }

    subdir = localPath === '/' ? '' : localPath;

    // Allow contentPath to be over-written by passed in config object
    // Otherwise default to default content path location
    contentPath = this._config.paths.contentPath || path.resolve(appRoot, 'content');

    assetHash = this._config.assetHash ||
        (crypto.createHash('md5').update(packageInfo.version + Date.now()).digest('hex')).substring(0, 10);

    if (!knexInstance && this._config.database && this._config.database.client) {
        knexInstance = knex(this._config.database);
    }

    _.merge(this._config, {
        database: {
            knex: knexInstance
        },
        ghostVersion: packageInfo.version,
        paths: {
            appRoot:          appRoot,
            subdir:           subdir,
            config:           this._config.paths.config || path.join(appRoot, 'config.js'),
            configExample:    path.join(appRoot, 'config.example.js'),
            corePath:         corePath,

            contentPath:      contentPath,
            themePath:        path.resolve(contentPath, 'themes'),
            appPath:          path.resolve(contentPath, 'apps'),
            imagesPath:       path.resolve(contentPath, 'images'),
            imagesRelPath:    'content/images',

            adminViews:       path.join(corePath, '/server/views/'),
            helperTemplates:  path.join(corePath, '/server/helpers/tpl/'),
            exportPath:       path.join(corePath, '/server/data/export/'),
            lang:             path.join(corePath, '/shared/lang/'),

            availableThemes:  this._config.paths.availableThemes || {},
            availableApps:    this._config.paths.availableApps || {},
            builtScriptPath:  path.join(corePath, 'built/scripts/')
        },
        theme: {
            // normalise the URL by removing any trailing slash
            url: this._config.url ? this._config.url.replace(/\/$/, '') : ''
        },
        slugs: {
            // Used by generateSlug to generate slugs for posts, tags, users, ..
            // reserved slugs are reserved but can be extended/removed by apps
            // protected slugs cannot be changed or removed
            reserved: ['admin', 'app', 'apps', 'archive', 'archives', 'categories', 'category', 'dashboard', 'feed', 'ghost-admin', 'login', 'logout', 'page', 'pages', 'post', 'posts', 'public', 'register', 'setup', 'signin', 'signout', 'signup', 'tag', 'tags', 'user', 'users', 'wp-admin', 'wp-login'],
            protected: ['ghost', 'rss']
        },
        uploads: {
            // Used by the upload API to limit uploads to images
            extensions: ['.jpg', '.jpeg', '.gif', '.png', '.svg', '.svgz'],
            contentTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml']
        },
        deprecatedItems: ['updateCheck', 'mail.fromaddress'],
        // create a hash for cache busting assets
        assetHash: assetHash
    });

    // Also pass config object to
    // configUrl object to maintain
    // clean dependency tree
    configUrl.setConfig(this._config);

    // For now we're going to copy the current state of this._config
    // so it's directly accessible on the instance.
    // @TODO: perhaps not do this?  Put access of the config object behind
    // a function?
    _.extend(this, this._config);
};
示例#28
0
'use strict';

var express = require('express');
var router = express.Router();
var knex = require('knex');
var config = require('../knexfile');
require('dotenv').config();
var environment = process.env.NODE_ENV || 'development';
var db = knex(config[environment]);
var checkit = require('checkit');




// back from google with info
// query database for username
// /usercheck

// if user exists then go to user home page
// /username
router.use('/:username', function(req, res, next) {
    if (req.session.passport.user.username === req.params.username) {
        next();
    } else {
        res.redirect('/');
    }
});
router.get('/:username', function(req, res, next) {

    var newData = [];
    var userInfo = {};
示例#29
0
module.exports = function() {
	var db = knex({
        client: 'pg',
        connection: config.db  
	});
}
示例#30
0
import knex from 'knex';
import bookshelf from 'bookshelf';

import databaseConfig from './database';

/*
 * Reference
 * Bookshelf (ORM): http://bookshelfjs.org/
 */

export default bookshelf(knex(databaseConfig.development));