Search code examples
node.jsbookshelf.jsknex.js

How to specify float precision in knex schema ?


I'm having trouble defining float precision in a knex schema, i want it to be a float(10,6) in order to store lat/long location. Here's how im trying to declare it :

lat: {type: 'float(10,6)', nullable: false},

It fails at migrate because of the (10,6), so how is the right way to do this ?


Solution

  • I don't know about this JSON approach since I only use the Schema Builder one.

    It looks like (example geostuff table with id, lat and lng columns):

    var knex = require('knex')({client:'sqlite3',connection:{filename: 'sample.sqlite3'}});
    
    knex.schema.createTable('geostuff', function(table) {
      table.increments('id').primary();
      table.float('lat', 14, 10).notNullable();
      table.float('lng', 14, 10).notNullable();
    }).then(function() {
      console.dir('table created');
    }).catch(function(err) {
      console.log('table not created');
      console.dir(err);
    });
    

    Note the precision specifiers are not widely supported. PostgreSQL supports float(precision), but SQLite3 (from the example), doesn't (better yet: does not care). Fortunately knex.js hides those idiosyncrasies.