Tuesday 22 December 2015

Get oracle version number in linux shell script

Get oracle version number in linux shell script

below command will provide you the version number as output
just make sure that your ORACLE_HOME path is set in ~/.base_profile file.

you can check it by

echo $ORACLE_HOME


echo $ORACLE_HOME | awk -F "/product/" '{print $2}' | cut -d'/' -f1

Sunday 27 September 2015

Get all connected user session list in oracle and kill oracle session


Get list of session active in oracle

you can get the list of active session from v$session table;


select 'alter system kill session '''|| sid ||',', serial#||'''' from v$session;


Kill the active session in oracle 

below statement will kill the live session.

alter system kill session '325,250';


Tuesday 22 September 2015

Convert csv to xml in java

Convert csv to xml in java

   here i have used opencsv-2.2.jar library for converting csv file into xml.

CsvToXmlConvert.java

package com.convert;

import java.io.File;
import java.io.FileReader;


import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import au.com.bytecode.opencsv.CSVReader;

public class CsvToXmlConvert {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        StringBuilder xml = new StringBuilder();
         String startFile = "/Book1.csv";
       
            try {
               
                File file=new File(request.getRealPath(startFile));
                CSVReader reader = new CSVReader(new FileReader(file));
               
                String[] line = null;
                String[] header = reader.readNext();
                Document doc = docBuilder.newDocument();
               
                Element rootElement = doc.createElement("Result");
                doc.appendChild(rootElement);
                Element Employees = doc.createElement("Employees");

                while((line = reader.readNext())!=null){
                   
                    Element Employee = doc.createElement("Employee");
                       
                    for (int i = 0; i < header.length; i++) {
                   
                        Element elm = doc.createElement(header[i].trim());
                        elm.appendChild(doc.createTextNode(line[i].trim()));
                        Employee.appendChild(elm);
                       
                    }
                       
                    Employees.appendChild(Employee);
                }
               
                rootElement.appendChild(Employees);
               
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File("/home/file.xml"));
                transformer.transform(source, result);
               
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

}





CSV FILE FORMATE

Book1.csv

FirstName, LastName, Number
Pushpak, Khatri, 9999999999
Raj,Patel, 9999999999
Simran, Khanna, 9999999999



Sunday 20 September 2015

Paging with oracle


Paging with Oracle


SELECT * FROM
(
    SELECT ID, rownum r__
    FROM
    (
        SELECT ID FROM SUBSCRIBER order by id) a
    WHERE rownum < ((:page * :pageSize) + 1 )
)
WHERE r__ >= (((:page-1) * :pageSize) + 1)

Friday 4 September 2015

Merge two json/javascript arrays in to one array

Merge two json/javascript arrays in to one array



(function($){$.concat||$.extend({concat:function(b,c){var a=[];for(var x in arguments)if(typeof a=='object')a=a.concat(arguments[x]);return a}});})(jQuery);

$(function() {
    var json1 = [{id:1, name: 'xxx'}],
        json2 = [{id:2, name: 'xyz'}],
        json3 = [{id:3, name: 'xyy'}],
        json4 = [{id:4, name: 'xzy'}],
        json5 = [{id:5, name: 'zxy'}];
   
    console.log($.concat(json1, json2, json3))
    console.log($.concat(json1, json2, json3, json4, json5))
    console.log($.concat(json4, json1, json2, json5))
});

Thursday 11 June 2015

Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING



Fix ‘Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING’ error on Chrome


Laravel is a great PHP framework and sometimes you might want to use it to power a website on a shared/cloud hosting service such as Rackspace Cloud Sites instead of a hosting service like Pagodabox which is better suited for hosting web apps. I certainly tried doing this when I set up a website powered by Laravel on my cloud site. 
Nevertheless,  even after setting everything up properly I encountered some very mysterious, and very annoying behavior using the Google Chrome browser that drove me nuts because my web pages only partially loaded and the JavaScript didn’t seem to fully execute code that was supposed to run on page load.
Naturally, I opened the Google Chrome browser developer console panel and found this rather strange looking error being logged:  failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
Frankly, I’m not entirely sure what it means even after Googling around for a solution and if you do know what it means I’d love to hear it in the comments. Nevertheless, after trying a few things I stumbled upon the solution of how to fix the problem across a couple of forum posts. It turns out that sometimes the Xcache PHP extension can sometimes cause this error  and that disabling it locally within the .htaccess file will fix the problem.
Sure enough,  I checked the output of a phpinfo() statement on a PHP script and found the Xcache module installed an enabled.  All I needed to do after determining this PHP extension was installed then was to disable Xcache within the .htaccess  file which is done by using php_flag values and adding them to your .htaccess file like so:
After doing this,  dumping the cache on the browser and reloading the page the error went away,  the page loaded normally and the JavaScript executed as expected. 
you can also write below code on your page 
ini_set(‘xcache.size’, 0);
ini_set(‘xcache.cacher’, ‘off’);
ini_set(‘xcache.stat’, ‘off’);

 

Thursday 14 May 2015

Lower Bound in Java With Example

Lower Bound in Java With Exampl

You can use an lower bounded wildcard to put the restrictions on a variable. For example, say you want to write a method that works on List<Integer>,List<Number> and List<Object> or — anything that can hold Integer values. Only; you can achieve this by using lower bounded wildcard.

To declare an lower-bounded wildcard, use the wildcard character ('?'), followed by the super keyword, followed by its lower bound.

To write the method that works on lists of Integer and the supertypes of Integer, such as Integer, Number, and Object, you would specify List<? super Integer>. The termList<Integer> is more restrictive than List<? super Integer> because the former matches a list of type Integer only, whereas the latter matches a list of any type that is a supertype of Integer.

Consider the following showNumbers method for Example:

we have used List<? super Integer> which will allow us to pass list of all the Call which is super class of Integer. so here when you call showNumbers Method then you can pass List of type List<Integer>, List<Number>, List<Object>.


import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        List<Object> li=new ArrayList<Object>();
       
        for (int i = 1; i <= 10; i++) {
        li.add(i);
        }
    HelloWorld.addNumbers(li);
       
     }
    
     public static void addNumbers(List<? super Integer> list) {
    for (int i = 0; i <= list.size()-1; i++) {
         System.out.println(list.get(i));
         }
}
}

Upper Bound in Java With Example


Upper Bound in Java With Exampl

You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number>; you can achieve this by using an upper bounded wildcard.

To declare an upper-bounded wildcard, use the wildcard character ('?'), followed by the extends keyword, followed by its upper bound. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

To write the method that works on lists of Number and the subtypes of Number, such as Integer, Double, and Float, you would specify List<? extends Number>. The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses.

Consider the following showNumbers method for Example:

 we have used List<? extends Number> which will allow us to pass list of all the Call which is derived from Number all whose super class is Number. so here when you call showNumbers Method then you can pass List of type List<Integer>, List<Float>, List<Double>, List<Number>, etc.. which includes Number class as parent Class.

HelloWorld.java

import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        List<Double> li=new ArrayList<Double>();
       
        for (double i = 1; i <= 10; i++) {
               li.add(i);
        }

        HelloWorld.addNumbers(li);
       
     }
    
     public static void showNumbers(List<? extends Number> list) {
     for (int i = 0; i <= list.size()-1; i++) {
         System.out.println(list.get(i));
         }
     }
}

Sunday 10 May 2015

populate dropdown using ajax in java

Populate Dropdown Using Ajax In Java

Here i have created some code which will bring the data using ajax from your controller of spring to your view and populate dropdown on the view.

Below is the controller method from where we are returning data to generate dropdown on view.  

Controller method

@RequestMapping(value="/getAddressList",method=RequestMethod.POST)
    public void getAddressList(Map<String, Object> map,HttpServletRequest request,HttpServletResponse response) throws IOException {
       
       
        List<WebAddress> addresses=new ArrayList<WebAddress>();
        for (Address add : addressService.listAddress()) {
                    WebAddress wadd=new WebAddress();
                    wadd.setId(add.getId());
                    wadd.setAddress1(add.getAddress1());
                    wadd.setAddress2(add.getAddress2());
                    wadd.setCity(add.getCity());
                    //wadd.setContacts(add.getContacts());
                    wadd.setState(add.getState());
                    wadd.setZip(add.getZip());
                    addresses.add(wadd);
        }
       
       
        Gson gson=new Gson();
   
       
        response.getWriter().write(gson.toJson(addresses));
    }



Now we are writing view and ajax call which will get the data and populate the dropdown on view.
for that we will create one select tag with ID let take dropdownID and then we will add options to this select box using jquery / javascript as Below

JSP view and page script
 

<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {


        $.ajax({
            type : "POST",
            dataType : 'json',
            url : "http://localhost:8080/getAddressList",
            success : function(data) {
                console.log(data);
                alert(data[0].address1);
                var options="<option value=''>--select country--</option>";
                $.each(data,function(k,v){
                    options +="<option value="+v.id+">"+v.address1 +","+v.address2+","+v.city+"</option>";
            
                    });         

                   $("dropdownID").html(options);
                }
        });
       
    });

</script>


<!--------your other html code -------->

<select id="dropdownID"></select>

<!--------your other html code -------->


[ERROR] Nested in org.springframework.web.util.NestedServletException: Request p rocessing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: 'xxxxxxxx', no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collect ion of role: 'xxxxxxxx', no session or session was c losed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia lizationException(AbstractPersistentCollection.java:383) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia lizationExceptionIfNotConnected(AbstractPersistentCollection.java:375) at org.hibernate.collection.AbstractPersistentCollection.initialize(Abst ractPersistentCollection.java:368) at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPe rsistentCollection.java:111) at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:27 2) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:95) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:60) at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ eAdapterRuntimeTypeWrapper.java:68) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(Re flectiveTypeAdapterFactory.java:89) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.wr ite(ReflectiveTypeAdapterFactory.java:195) at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapt er.java:107) at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ eAdapterRuntimeTypeWrapper.java:68) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:96) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:60) at com.google.gson.Gson.toJson(Gson.java:593) at com.google.gson.Gson.toJson(Gson.java:572) at com.google.gson.Gson.toJson(Gson.java:527) at com.google.gson.Gson.toJson(Gson.java:507) at net.demo.contact.controller.ContactController.getAddressList(ContactC ontroller.java:64) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:43)

[ERROR] Nested in org.springframework.web.util.NestedServletException: Request p
rocessing failed; nested exception is org.hibernate.LazyInitializationException:
 failed to lazily initialize a collection of role: net.demo.contact.form.Address
.contacts, no session or session was closed:
org.hibernate.LazyInitializationException: failed to lazily initialize a collect
ion of role: net.demo.contact.form.Address.contacts, no session or session was c
losed
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia
lizationException(AbstractPersistentCollection.java:383)
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia
lizationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
        at org.hibernate.collection.AbstractPersistentCollection.initialize(Abst
ractPersistentCollection.java:368)
        at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPe
rsistentCollection.java:111)
        at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:27
2)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:95)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ
eAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(Re
flectiveTypeAdapterFactory.java:89)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.wr
ite(ReflectiveTypeAdapterFactory.java:195)
        at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapt
er.java:107)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ
eAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:96)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.Gson.toJson(Gson.java:593)
        at com.google.gson.Gson.toJson(Gson.java:572)
        at com.google.gson.Gson.toJson(Gson.java:527)
        at com.google.gson.Gson.toJson(Gson.java:507)
        at net.demo.contact.controller.ContactController.getAddressList(ContactC
ontroller.java:64)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.
invokeHandlerMethod(HandlerMethodInvoker.java:174)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandle
rAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandle
rAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(Dispatch
erServlet.java:771)


SOLUTION

You are getting this error because, when you are trying to return a data in JSON or GSON from controller. you are returning the object which is provided by the service. and this object contains dependencies of other objects like if we have used any relationships (@OneToMany or @ManyToMany or @ManyToOne or @OneToOne ) in the object so when we are converting this object to JSON or GSON it is going into that all dependencies to get the data. so we are getting this error of  nested exception is org.hibernate.LazyInitializationException.

to solve this you can do below thing.

STEP - 1 ) Create SIMPLE POJO class with all the fields which you want in your JSON data like..

  I have one model which i want to return named Contactas below but we have used we have used @ManyToOne dependency in this so when we will try to return it directly we will get above error. so now see the next step.

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="CONTACTS")
public class Contact implements Serializable  {
    private static final long serialVersionUID = 1L;
   
    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;
   
    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;
   
    @Column(name="TELEPHONE")
    private String telephone;
   
    @ManyToOne
    private Address address;
   
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
   
}

STEP-2 ) Create simple POJO class of model but without hibernate annotation like.

public class ContactPOJO  {
    private Integer id;
   
    private String firstname;

    private String lastname;

    private String email;
   
    private String telephone;
   
    private Address address;
   
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
   
}

STEP - 3 ) Now use this class to return the data as i have used below.

  try {
            Gson gson=new Gson();
            Contact c=contactService.getContactById(contactId);  //////Object which are receiving from service

            ContactPOJO wc=new ContactPOJO();                   ///// Object we create to return in json formate
            wc.setId(c.getId());
            wc.setFirstname(c.getFirstname());
            wc.setLastname(c.getLastname());
            wc.setEmail(c.getEmail());
            wc.setTelephone(c.getTelephone());
            wc.setAddressId(c.getAddress().getId());

            response.getWriter().write(gson.toJson(wc));

        } catch (IOException e) {
            e.printStackTrace();
        }

STEP - 4 ) Now you will not get the error.

Please follow if you like this. contact me you need some help.




spring mvc dropdown onchange example

spring mvc dropdown onchange example

In Spring controller , write below code to bind the <form:select />, <form:option /> or <form:options />, we will use bellow value to render HTML form:select box :

@Controller

@RequestMapping("/")

public TestController{

protected ModelAndView createSelectWithValue(HttpServletRequest request) throws Exception { 
 
        Map cData = new HashMap(); 
 
        Map<String,String> countryList = new LinkedHashMap<String,String>(); 
 
        countryList.put("TX", "Texas");
 countryList.put("IN", "India");
 countryList.put("NY", "New York");
 countryList.put("NJ", "New Jessy");
 cData.put("cList", countryList); 
  
        ModelAndView mav=new ModelAndView();
        mav.addAttribute("selectedCountry","IN"); 
        mav.addAttribute("cList",cData);
        mav.setView("index");
  
        return mav;
  }
}
 
 
index.jsp
 
1) javascript which we will call onchange of spring mvc dropdown (<form:select />)
  
 <script type="text/javascript">

 function getValue(obj)
 {
  alert("You have selected Country: " + obj.value);
 }
 
</script>
 
2) spring mvc dropdown with onchange event
 
   <select id="country" name="country" onchange="getValue(this);"> 
 
      <option value="">--select country--</option>
 
      <c:forEach items="${cList}" var="name"> 
 
            <option value="${name[0]}" >${name[1]}</option>
        
      </c:forEach>
  </select> 
 
 
 
 

Wednesday 6 May 2015

basic authentication in express nodejs

Basic Authentication In Express Nodejs

To set a basic authentication to your project in node js. you need to have below modules.

npm install express --save
npm install basic-auth --save

Now use this module in your application

server.js

var express = require('express');
var auth = require('basic-auth');
var app = express();


app.use(function (req, res, next) {

    var user = auth(req);
    if (user === undefined) {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="et3ebs6126a"');
        res.end('Unauthorized');
     } else
     {
        obj = new Object();
        obj.name = user['name'];
        obj.passkey = user['pass'];
                   console.log("Check Login");
            if(obj.name=="USERNAME" and obj.passkey="PASSWORD")
            {
                next();
            } else
            {
                res.statusCode = 401;
                res.setHeader('WWW-Authenticate', 'Basic realm="et3ebs6126a"');
                res.end('Unauthorized');
           }
    }
   
});



When ever you will try to open your project it will ask for authentication.

basic-auth-with-express-nodejs

Tuesday 5 May 2015

knex seed using nodejs example

Creating Seed for using Migrations in Knex

Migrations allow for you to define sets of schema changes so upgrading a database is a breeze.

Migration CLI

The migration CLI is bundled with the knex install, and is driven by the node-liftoffmodule. To install globally, run:
$ npm install knex -g
 
The 0.6 migrations use a knexfile, which specify various configuration settings for the module.
To create a new knexfile, run the following:
$ knex init

will create a sample knexfile.js - the file which contains our various database configurations. Once you have a knexfile.js, you can use the migration tool to create migration files to the specified directory (default migrations). Creating new migration files can be achieved by running:
$ knex migrate:make your_migration_name
Once you have the migrations in place you wish to run, you can run:
$ knex migrate:latest
To update your database to the latest version.

Seed files

Seed files allow you to populate your database with test or seed data independent of your migration files.

Seed CLI

To create a seed file, run:
$ knex seed:make your_seed_name
 
Seed files are created in the directory specified in your knexfile.js for the current environment.
A sample seed configuration looks like:
 
development: {
  client: ...,
  connection: { ... },
  seeds: {
      directory: './seeds/dev'
  }
}
 
If no seeds.directory is defined, files are created in ./seeds.
Note that the seed directory needs to be a relative path. Absolute paths are not supported (nor is it good practice).
Your seed file will contain the code like
'use strict';
exports.seed = function(knex, Promise) {
    return Promise.join(
        // Deletes ALL existing entries
        knex('users').del(),

        // Inserts seed entries
        knex('users').insert({user_name: 'testUserBySeed', passkey: 'passkey'})
       
    );
};
 
To run seed files, execute:
$ knex seed:run
 
Seed files are executed in alphabetical order. Unlike migrations, every seed file will be executed when you run the command. You should design your seed files to reset tables as needed before inserting data.

knexfile.js

A knexfile.js or knexfile.coffee generally contains all of the configuration for your database. It can optionally provide different configuration for different environments. You may pass a --knexfile option to any of the command line statements to specify an alternate path to your knexfile.

Basic configuration:

module.exports = {
  client: 'pg',
  connection: process.env.DATABASE_URL || {
    username: 'me',
    database: 'my_app'
  }
};

Environment configuration:

module.exports = {
  development: {
    client: 'pg',
    connection: {
      username: 'me',
      database: 'my_app'
    }
  },
  production: {
    client: 'pg',
    connection: process.env.DATABASE_URL
  }
};

Migration API

knex.migrate is the class utilized by the knex migrations cli. Each method takes an optional config object, which may specify specifies the database, directory,extension, and tableName for the migrations.
makeknex.migrate.make(name, [config]) 
Creates a new migration, with the name of the migration being added.
latestknex.migrate.latest([config]) 
Runs all migrations that have not yet been run.
rollbackknex.migrate.rollback([config]) 
Rolls back the latest migration group.
currentVersionknex.migrate.currentVersion([config]) 
Retrieves and returns the current migration version, as a promise. If there aren't any migrations run yet, returns "none" as the value for the currentVersion.

Seed API

knex.seed is the class utilized by the knex seed CLI. Each method takes an optionalconfig object, which may specify the relative directory for the migrations.
makeknex.seed.make(name, [config]) 
Creates a new seed file, with the name of the seed file being added.
runknex.seed.run([config]) 
Runs all seed files for the current environment.

Source code available at https://github.com/jayesh36/RESTFull-API-with-express-knex-promises-with-testcase-in-mocha