Remove the function after it being used for the first time - javascript

I have the simple SQL query builder that looks like this:
class QueryBuilder {
select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return this;
}
from(table) {
this.query += "FROM `" + table + "` ";
return this;
}
}
The problem is that it returns this so I'm able to do like:
const sql = builder.select("field1", "field2").from("table").select("I shouldn't be able to call select");
Is there any way to disable/remove the select function from Builder instance and autocomplete after calling it for the first time? Or to underscore that calling that function for the second time will cause an error.
Solution:
According to #Sohail answer, to make it works like that you just need to move from() from the QueryBuilder class and just return it as a field with the query as a new plain object:
class QueryBuilder {
static select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return {
query: this.query,
from
};
}
}
function from(table) {
this.query += "FROM `" + table + "` ";
return {
query: this.query,
where: function() {}
};
}

You could return the specific method instead of this, that could be called in chain after this method.
Example:
class QueryBuilder {
select(fields) {
this.query = "SELECT `" + fields.join("`, `") + "` ";
return {
from: this.from.bind(this)
};
}
from(table) {
this.query += "FROM `" + table + "` ";
return {
where : ""
};
}
}

You can try below modification:
select(fields) {
if(!this.query.includes("SELECT")){
this.query = "SELECT `" + fields.join("`, `") + "` ";
}
return this;
}

Related

Unable to send dynamic invoice value to struts2 server

I am working on angularjs 1.6.5
I am using following code to send data of invoice page.
$scope.products = [{qty: 0, description: ' ', sellingPrice: 0.0, unitPrice: 0.0, total: 0.0}];
$scope.fproducts = [];
$scope.generateInvoice = function () {
console.log("generateInvoice");
console.log($scope.fproducts);
console.log("sub total " + $scope.subTotal + " ft " + $scope.finalTotal + " pamt " + $scope.paidAmount + " baldue " + $scope.balancedue);
$scope.bd1 = {
'subTotal': $scope.subTotal,
'total': $scope.finalTotal,
'TotalPaid': $scope.paidAmount,
'invDateStr': $filter('date')($scope.invoiceDate, "MM/dd/yyyy"),
};
if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}].${key}`] = value;
});
});
}
//commenting above for each and removing comment from below code is
// working properly but I want to send dynamic data with above code
/* $scope.bd1[`billProductList[0].id`] = 1;
$scope.bd1[`billProductList[0].description`] = 1;
$scope.bd1[`billProductList[0].discountPercent`] = 150;
$scope.bd1[`billProductList[0].qty`] = 10;
$scope.bd1[`billProductList[0].sellingPrice`] = 100;
$scope.bd1[`billProductList[0].unitPrice`] = 100;
$scope.bd1[`billProductList[0].total`] = 150;*/
$scope.bd1[`BillPaidDetailses[0].paymentMode`] = $scope.paymentMode;
$scope.bd1[`BillPaidDetailses[0].amount`] = $scope.paidAmount;
console.log($scope.bd1);
$http({
method: 'POST',
url: 'added-invoice',
data: $httpParamSerializerJQLike($scope.bd1),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(data, status, headers, config) {
if (data.data.st === 1) {
$scope.success = true;
window.location = 'bhome#!/show-tax';
} else if (data.data.st === 0) {
$scope.success = false;
$scope.failure = true;
} else if (data.data.st === -1) {
$scope.success = false;
$scope.failure = true;
}
}, function errorCallback(data, status, header, config) {
$scope.success = false;
$scope.failure = true;
});
}
Above code is not passing value to server side object.
its console.log value is
on modifying above data
/*if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}].${key}`] = value;
});
});
}*/
$scope.bd1[`billProductList[0].id`] = 1;
$scope.bd1[`billProductList[0].description`] = 1;
$scope.bd1[`billProductList[0].discountPercent`] = 150;
$scope.bd1[`billProductList[0].qty`] = 10;
$scope.bd1[`billProductList[0].sellingPrice`] = 100;
$scope.bd1[`billProductList[0].unitPrice`] = 100;
$scope.bd1[`billProductList[0].total`] = 150;
as this is passing value to server object
its console.log is
I want to run my code using dynamic value specified in if condition.
What is the problem I am unable to get it.
EDIT I am using server side struts2
my code is
public class BillNewAction extends ActionSupport implements ModelDriven<BillDetails> {
BillDetails bd = new BillDetails();
private List<BillDetails> billList = new ArrayList<BillDetails>();
public String insert() {
System.out.println("total " + bd.getTotal()
+ " subTotal " + bd.getSubTotal() + " paid "
+ bd.getTotalPaid()
+ " invoiceDate " + bd.getInvDateStr()
);
SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
try {
bd.setInvoiceDate((new java.sql.Date(formatter1.parse(bd.getInvDateStr()).getTime())));
} catch (ParseException ex) {
Logger.getLogger(BillNewAction.class.getName()).log(Level.SEVERE, null, ex);
}
for (BillPaidDetails b : bd.getBillPaidDetailses()) {
System.out.println("type " + b.getPaymentMode() + " amount "
+ b.getAmount()
);
}
System.out.println("product size " + bd.getBillPrList().size());
for (BillProduct b : bd.getBillPrList()) {
System.out.println("id " + b.getId() + " desc "
+ b.getDescription() + " qty " + b.getQty()
+ " sp " + b.getSellingPrice() + " up "
+ b.getUnitPrice() + " " + b.getTotal()
);
}
}
}
public class BillDetails implements java.io.Serializable {
private Long billNo;
private Client client;
private BigDecimal subTotal;
private BigDecimal TotalAmount;//total price
private BigDecimal TotalPaid;//Amount paid for getting items
private BigDecimal vat;
private BigDecimal total;
private String invoiceNo;
private Date invoiceDate;
private String invDateStr;
private List<BillPaidDetails> BillPaidDetailses = new ArrayList<BillPaidDetails>();
private List<BillProduct> billPrList = new ArrayList<BillProduct>();
//getter and setter
}
I have to send data in $scope.bd1[billProductList[0].id] = 1; format to server
Assigning indivisual value passing the data to server but I have dynamic no of values so I am trying
if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[billProductList[${index}].${key}] = value;
});
});
}
that is not working
Consider using the Struts JSON Plugin
The JSON plugin provides a json result type that serializes actions into JSON.
The content-type must be application/json
Action must have a public “setter” method for fields that must be populated.
Supported types for population are: Primitives (int,long…String), Date, List, Map, Primitive Arrays, other class, and Array of Other class.
Any object in JSON, that is to be populated inside a list, or a map, will be of type Map (mapping from properties to values), any whole number will be of type Long, any decimal number will be of type Double, and any array of type List.
Your actions can accept incoming JSON if they are in package which uses json interceptor or by adding reference to it.
This simplifies the AngularJS HTTP POST request:
$scope.bd1 = {
'subTotal': $scope.subTotal,
'total': $scope.finalTotal,
'TotalPaid': $scope.paidAmount,
'invDateStr': $scope.invoiceDate.toISOString(),
'billProductList': $scope.fproducts,
};
$http({
method: 'POST',
url: 'added-invoice',
data: $scope.bd1,
headers: {'Content-Type': 'application/json'}
}).then(function successCallback(response) {
var data = response.data;
if (data.st === 1) {
$scope.success = true;
window.location = 'bhome#!/show-tax';
} else if (data.st === 0) {
$scope.success = false;
$scope.failure = true;
} else if (data.data.st === -1) {
$scope.success = false;
$scope.failure = true;
}
}, function errorCallback(response) {
$scope.success = false;
$scope.failure = true;
});
$scope.bd1[billProductList[${index}].${key}] = value; you are overriding value on this line of code
$scope.bd1[billProductList[${index}${index2}].${key}] you can change shape of object as per you need
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value],index2) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}${index2}].${key}`] = value;
});
})
That may be because console.log(index + " " + key + " " + value) is returning correct value as you are getting inside loop.
try to access the below piece of code, after assigning to $scope.bd1:
Object.entries(total).forEach(([key, value]) => {
$scope.bd1[`billProductList[${index}].${key}`] = value;
console.log($scope.bd1[`billProductList[${index}].${key}`]);
});
And I guess $scope.bd1 is not getting updated hence it is not passing value to server side object.

Sqlite Select query with where condition doesn't return any value

I've tried all possible formats for the select query:
var queryCust = "SELECT * FROM customers WHERE CustBarcode = '" + CustomerBarcode + "';";
or
var queryCust = "SELECT * FROM customers WHERE CustBarcode like '" + CustomerBarcode + "';";
or
var queryCust = "SELECT * FROM customers WHERE cast(CustBarcode as text) = '" + CustomerBarcode "';";
or with and without ' ' but nothing works, the query didn't return any value!
I've even tried
db.executeSql('SELECT * FROM customers WHERE CustBarcode = ?', [ CustBarcode ], function(rs) {...
but didn't worked, even when tried to convert with javascript CustBarcode to string or integer.
below is the function:
alert(queryCust);
db.executeSql(queryCust, [], function(rs) {
alert(rs.rows.item(0).CustBarcode);
var DescCust = "";
if (rs.rows.item(0).Status == 'NEW'){
DescCust = rs.rows.item(0).Desc + ' ' + rs.rows.item(0).Address;
} else {
DescCust = rs.rows.item(0).CustCode + ' ' + rs.rows.item(0).Desc + ' ' + rs.rows.item(0).Address;
}
document.getElementById("custDesc").innerHTML = DescCust;
}, function(error) {
alert('SELECT SQL statement ERROR while building DescCust: ' + error.message);
});

prepared statement node sqlite3 and Like keyword

Im trying to create a function that lets me search and order a list using Node and SQLite3. Im not quite sure what I am doing wrong, but when I include the sort parameter the code stops working and I get "Error: SQLITE_ERROR: Near "?": syntax error".
This is the code.
exports.search = function(name, sort, sortAscDesc, cb) {
var sqlQuery = "SELECT * FROM Crimestat";
if (name != undefined) {
name = "%" + name + "%";
sqlQuery += " WHERE municipacility LIKE ?";
}
if (sort != undefined) {
if (sortAscDesc != undefined) {
sqlQuery += " ORDER BY ? ?";
} else {
sqlQuery += " ORDER BY ASC";
}
}
console.log("sql query " + sqlQuery)
db.all(sqlQuery, name, sort, sortAscDesc, function(err, row) {
if (row == undefined) {
console.log("error " + err)
cb(false);
} else {
cb(row);
}
});
Thank you in advance

Node sqlite3 when to close db

I cannot figure out when to close a db in node-sqlite3, or really how to use the package in general. It seems if I run this, I get "no such table:rooms". Eventually after running it enough times, I might manage to make the table.
var sqlite3 = require('sqlite3').verbose();
class RoomManager{
constructor(options){
this.db = this._createDb();
this.table = "rooms";
this._createTable();
this.addRoom({
name : 'test3'
}).getRooms()
this.deleteRoom({
name : 'test3'
}).getRooms();
return this;
}
_createDb() {
return new sqlite3.Database('chat');
}
_createTable(){
this.db.run("CREATE TABLE IF NOT EXISTS " + this.table + " (name TEXT, size INT)");
return this;
}
addRoom(options){
this.db.run("INSERT INTO " + this.table + " (name, size) VALUES ($name, $size)", {
$name : options.name,
$size : options.size || 1000
});
return this;
}
getRooms(){
this.db.all("SELECT rowid, name, size FROM " + this.table, function(err, rows) {
rows.forEach(function (row) {
console.log(row.rowid + ": " + row.name + " - " + row.size);
});
});
return this;
}
getRoom(options){
if(options.name){
this.db.get("SELECT * FROM " + this.table + " WHERE name = $name", {
$name : options.name
}, function(err, row){
return row;
});
}
}
deleteRoom(options){
this.db.run("DELETE FROM " + this.table + " WHERE name = $name", {
$name : options.name
});
return this;
}
}
module.exports = RoomManager;
Your problem that Node is asynchronous. So, you must wait end of command by callback function. e.g.
this.db.run(query, params, function(err) {
if (err)
return console.log(err);
// do next query here
})
Sqlite module can control flow by db.serialize. Imho it's useless in common cases. Better use async module or promises for it.

javascript get selected value from form (in Netbeans web project with DB)

I need little help.
First, I have page with some values from Database in form, like this:
out.println("<form method=\"post\" action=\"update.jsp?id=" +
rs.getString(1) +"\" onSubmit=\"return editF(this)\" id=\"editDiv"+ rs.getString(1) +"\" >" + SelectCat() +" </form>")
public String SelectCat()
{
String result = "<select name=\"category\" >";
try
{
String request = "SELECT * FROM cat";
Statement st = getConnection().createStatement();
ResultSet rs = st.executeQuery(request);
while (rs.next())
{
result += "<option value=\"" + rs.getString(1) + "\">" + rs.getString(2) + "</option>";
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
result += "</select>";
return result;
}
And my javascript function is
function editF(form)
{
alert("a");
string header = form.header.value;
string text = form.text.value;
string category = form.category.selectedIndex.value;
var e = document.getElementByName("category");
//var category = e.selectedIndex;
form.action = form.action + "&header="+header+"&text="+text+"&categoryID="+category;
return true;
};
But I can't get selected value.
Can you help me?
Thanks!
var category = form.category.options[ form.category.selectedIndex ].value;
Also, javascript is not a strongly-typed language, you cannot define its type when declaring it. Instead, use var.

Categories