Guest User

Untitled

a guest
Apr 28th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. var connectionString = 'postgres://localhost:5432/postgres';
  2. var Promise=require('bluebird');
  3.  
  4.  
  5. var knex = require('knex')({
  6. client: 'pg',
  7. connection: {
  8. user: 'postgres',
  9. database: 'postgres',
  10. port: 5432,
  11. host: 'localhost',
  12. password: 'admin'
  13. },
  14. debug: false,
  15. pool: {
  16. min: 1,
  17. max: 2
  18. }
  19. });
  20.  
  21.  
  22. var books = [
  23. { name: 'Da vinci', author: { 'first_name': 'Bob', last_name: "White" }},
  24. { name: '50 shades of blue', author: { 'first_name': 'Bob', last_name: "Heinzeberg" }}
  25. ];
  26.  
  27. // Create table with json data column
  28. var schemaCreation =function() {
  29.  
  30. return knex.schema.dropTableIfExists('books')
  31. .then(function() {
  32. return knex.schema.createTable('books',function(table){
  33. table.increments();
  34. table.timestamps();
  35. table.json('data').nullable();
  36. });
  37. });
  38.  
  39. };
  40.  
  41.  
  42. // Insert the books
  43. var inserts = function() {
  44. var insertPromises = [];
  45. books.forEach(function(book) {
  46.  
  47. insertPromises.push(
  48. knex('books')
  49. .insert({data: JSON.stringify(book), created_at : new Date(), updated_at: new Date() })
  50. );
  51. });
  52.  
  53. return Promise.all(insertPromises);
  54. };
  55.  
  56.  
  57.  
  58. // Perform some selects on json
  59. var selects = function() {
  60.  
  61. return knex('books').select(knex.raw("data->'author' as author")).whereRaw("data->'author'->>'first_name'=? ",[books[0].author.first_name])
  62. .then(function(rows) {
  63. console.log("Found "+rows.length+" books with authors first_name "+books[0].author.first_name);
  64. rows.forEach(function(row){
  65. console.log(row);
  66. });
  67. })
  68. .then(function() {
  69. return knex('books').select(knex.raw("data->'author' as book")).whereRaw("data->'author'->>'last_name'=? ",[books[0].author.last_name])
  70. .then(function(rows) {
  71. console.log("Found "+rows.length+" book(s) with last_name "+books[0].author.last_name);
  72. console.log(rows[0]);
  73. });
  74. });
  75.  
  76. };
  77.  
  78. // Main flow
  79. schemaCreation()
  80. .then(function() {
  81. console.log('Table created');
  82. })
  83. .then(inserts)
  84. .then(function() {
  85. console.log('Inserts done');
  86. })
  87. .then(selects)
  88. .then(function() {
  89. process.exit(0);
  90.  
  91. })
  92. .catch(function(error){
  93. console.log(error);
  94. });
Add Comment
Please, Sign In to add comment