Mad Bernard
Mad Bernard

Reputation: 372

Syntax for creating database and schemas with knex and bookshelf?

I have some working code that uses knex and bookshelf to set up a Sqlite3 database and tables. It doesn't look like what I'm seeing on the Bookshelf website, though. This blog post seems to indicate that creating things is knex's job, but I don't see Bookshelf.conn stuff on the Bookshelf website either. Can I use something like this code to create a Postgres database and tables?

This is the code that worked (package.json has "knex": "~0.5.7" and "bookshelf": "~0.6.4", currently they're both at 0.9):

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

var db = Bookshelf.initialize({
  client: 'sqlite3',
  connection: {
    host: '127.0.0.1',
    user: 'your_database_user',
    password: 'password',
    database: 'database_name',
    charset: 'utf8',
    filename: path.join(__dirname, '../db/mydb.sqlite')
  }
});

db.knex.schema.hasTable('urls').then(function(exists) {
  if (!exists) {
    db.knex.schema.createTable('urls', function (link) {
      link.increments('id').primary();
      link.string('url', 255);
      link.string('base_url', 255);
      link.string('code', 100);
      link.string('title', 255);
      link.integer('visits');
      link.timestamps();
    }).then(function (table) {
      console.log('Created Table', table);
    });
  }

module.exports = db;

Upvotes: 0

Views: 2951

Answers (3)

vbranden
vbranden

Reputation: 5986

var  knex = require('knex')(
{
  client: 'postgresql',
  connection: {
    host     : '127.0.0.1',
    user     : 'your_database_user',
    port     : '5432',
    password : 'your_database_password',
    database : 'myapp_test',
    charset  : 'UTF8_GENERAL_CI'
  }
});
var bookshelf = require('bookshelf')(knex);

Upvotes: 0

Mad Bernard
Mad Bernard

Reputation: 372

Once I try to run the above code with the 0.9 versions of knex and bookshelf, I get the response "Bookshelf.initialize is deprecated, pass knex directly: require('bookshelf')(knex)". As mentioned in a comment, Bookshelf.initialize used "the already configured Knex instance internally in Bookshelf" but apparently sometime between March 2014 and now that fell by the wayside.

Upvotes: 0

barbarity
barbarity

Reputation: 2488

I'm not familiar with Bookshelf or Knex but have you tried this?

var db = Bookshelf.initialize({
  client: 'postgresql',
  connection: {
    host     : '127.0.0.1',
    user     : 'your_database_user',
    port     : '5432',
    password : 'your_database_password',
    database : 'myapp_test',
    charset  : 'UTF8_GENERAL_CI'
  }
});

Upvotes: 2

Related Questions