Parse MySQL queries, including JOINs - javascript

Is there an already built tool in PHP or Javascript that parses MySQL queries, including JOINs.
What I need as a result is simply two arrays:
The first is an array of the Query Result fields. (result[])
The second is an array of the Query Parameters. (params[])
Example:
Select PersonID,firstName,lastName,countryName
FROM Person
LEFT JOIN Country ON Person.countryID=Country.countryID
Where firstName="Jonathan" and countryName="Canada"
Would result in the following:
result=['PersonID','firstName','lastName','countryName'];
params=['firstName','countryName'];

This library would probably help you as it parse the query and return every information as an array: php-sql-parser

There is also a javascript library: javascript sql parser
The parser returns an object that contains all the information about the sql query. it supports for now only select statement.

Related

Java Script UDF in MySQL 8

I am migrating few queries from Google BigQuery to MySQL and need help in replicating the below BigQuery Java script UDF to equivalent MySQL. I don't see any reference over the internet. Does MySQL support Java Script UDFs ?
The requirement here is to Split a JSON array into a simple array of string ( each string represents individual JSON string ).
CREATE OR REPLACE FUNCTION `<project>.<dataset>.json2array`(json STRING) RETURNS ARRAY<STRING> LANGUAGE js AS R"""
if (json) {
return JSON.parse(json).map(x=>JSON.stringify(x));
} else {
return [];
}
""";
No, MySQL does not support JavaScript stored functions. MySQL supports stored functions written in a procedural language. It also supports server-loadable functions compiled from C or C++, but these are less common.
MySQL doesn't have an ARRAY data type. The closest you can get in MySQL is a JSON data type, which may be a one-dimensional array of strings. If your JSON document is assured to be an array in that format, then you can simply do the following:
CREATE FUNCTION json2array(in_string TEXT) RETURNS JSON DETERMINISTIC
RETURN CAST(in_string AS JSON);
I'm not sure what the point of creating a stored function is in this case, since it only does what CAST() can do. So you might as well just call CAST() and skip creating the stored function.
Perhaps a good use of a stored function is to test the input to make sure it's a document with an array format (use JSON_TYPE()). For example:
CREATE FUNCTION json2array(in_string TEXT) RETURNS JSON DETERMINISTIC
RETURN IF(JSON_TYPE(in_string) = 'ARRAY', CAST(in_string AS JSON), JSON_ARRAY());

How to use Prepared statements with npm sqlite library on node js

I am using this library for connecting my node js application to an sqlite database. I saw its documentation for how to use prepared statements here but it is very brief and I cannot understand how to use it for my use case.
Lets say I have an sql string like this:
const sql = "INSERT INTO tbl(name) VALUES (?)"
So as per the documentation guess I should first create a statement and then use bind to populate it:
const stmt = await db.prepare(sql)
stmt.bind({? : "John"})
Is this the right way to do this? Also once I have created the Prepared statement how am I supposed to run this. All the examples mentioned in the docs are select statements, but if it is an insert statement I suppose stmt.get() or stmt.all() method are not correct as there is no result set to return here. How then am I supposed to do this?
I don't know the sqlite library too well, but the following example from the documentation performs a parameterised INSERT statement:
const result = await db.run('INSERT INTO tbl(col) VALUES (:col)', {
':col': 'something'
})
I think you're focusing on the phrase 'prepared statement' a little too much.
Instead of looking only for this exact phrase, look for any use of parameters whose values are passed separately to the main SQL string. The example above fits this: there is a parameter :col which appears in the SQL string and the value for it is provided in an object passed to db.run alongside the SQL string.

How can a linq query be converted to JavaScript array containing only values?

I have a JavaScript grid library (it creates a table on the page) that accepts a JavaScript array as input, for rendering in the grid. I'm not certain, however, how to convert a Linq-to-SQL query (against a SQL Server database) to a JavaScript array containing only values.
I tried this, but it included the table column names in the JSON key (and I don't want JSON anyway, I want a JavaScript string array, unless this can be converted to an array?):
JsonConvert.SerializeObject(query)
Example of the format I need to produce:
[1,2,3],[4,5,6]
Environment: .NET Core 3.1
edit: Here is a sample of what I've currently got, this returns the less than desirable JSON (due to the query results being so large, having a JSON key for very element is going to literally double the size of the query):
Devices Table
ID Name
1 iPhone7
2 iPhone8
3 iPhone9
Needed Array (Note: no column names)
[1, "iPhone7"],[2, "iPhone8"],[3, "iPhone9"]
Current C# code in the controller method (returns undesirable key for every element currently)
var query = db.Devices;
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
Technically, you could do this:
var query = db.Devices.AsEnumerable()
.Select(d => new object[]{d.ID, d.Name});
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
But then the code on the other end of your request is going to have to translate all those arrays back into objects.
It's rarely worthwhile to complicate your model like this in order to optimize the size of your network traffic. If you're pulling enough items over the wire to make this a performance issue, you're likely to encounter a variety of other performance issues. I would first consider other options, like implementing paging.
Did you try
var query = db.Devices.ToList();
var array = JArray.FromObject(query);
return Ok(formattedResult)

MongoDB - How to build query string with [Object] as a field

I'm building up a string in Meteor to drill down into my data from MongoDB.
My data looks like this:
Data
In my Meteor projects JavaScript I have built up the string like so:
const concentrationTier1 = MyCollection.findOne({_id: "85gh43tnb23v4"}).BILL.Sovereign.USD.Short.Low.High.N.ARGENTINA.IssueName00006.ARARGE5203E7;
console.log(concentrationTier1);
But now in my console it is returning the following:
Console
How would I add [Object] to my string to be able to display the next part of the data?
I have tried .[Object] .Object .0 and of course these didn't work.
Can any body help with this one?
Many thanks,
G
You would have to access that array element as in plain normal javascript, like this:
...IssueName00006.ARARGE5203E7[0].concentrationTier1
And the reason is your MongoDB query already returned a document, you're not querying in your database anymore so there's no need to use dot notation to access array elements.

Lucene-like searching through JSON objects in JavaScript

I have a pretty big array of JSON objects (its a music library with properties like artist, album etc, feeding a jqgrid with loadonce=true) and I want to implement lucene-like (google-like) query through whole set - but locally, i.e. in the browser, without communication with web server. Are there any javascript frameworks that will help me?
Go through your records, to create a one time index by combining all search
able fields in a single string field called index.
Store these indexed records in an Array.
Partition the Array on index .. like all a's in one array and so on.
Use the javascript function indexOf() against the index to match the query entered by the user and find records from the partitioned Array.
That was the easy part but, it will support all simple queries in a very efficient manner because the index does not have to be re-created for every query and indexOf operation is very efficient. I have used it for searching up to 2000 records. I used a pre-sorted Array. Actually, that's how Gmail and yahoo mail work. They store your contacts on browser in a pre-sorted array with an index that allows you to see the contact names as you type.
This also gives you a base to build on. Now you can write an advanced query parsing logic on top of it. For example, to support a few simple conditional keywords like - AND OR NOT, will take about 20-30 lines of custom JavaScript code. Or you can find a JS library that will do the parsing for you the way Lucene does.
For a reference implementation of above logic, take a look at how ZmContactList.js sorts and searches the contacts for autocomplete.
You might want to check FullProof, it does exactly that:
https://github.com/reyesr/fullproof
Have you tried CouchDB?
Edit:
How about something along these lines (also see http://jsfiddle.net/7tV3A/1/):
var filtered_collection = [];
var query = 'foo';
$.each(collection, function(i,e){
$.each(e, function(ii, el){
if (el == query) {
filtered_collection.push(e);
}
});
});
The (el == query) part of course could/should be modified to allow more flexible search patterns than exact match.

Categories