Giter Site home page Giter Site logo

node-red-contrib-alasql's Introduction

CI-test NPM downloads OPEN open source software Release Average time to resolve an issue Coverage OpenSSF Scorecard OpenSSF Best Practices Stars

AlaSQL

AlaSQL logo

AlaSQL - ( à la SQL ) [ælæ ɛskju:ɛl] - is an open source SQL database for JavaScript with a strong focus on query speed and data source flexibility for both relational data and schemaless data. It works in the web browser, Node.js, and mobile apps.

This library is perfect for:

  • Fast in-memory SQL data processing for BI and ERP applications on fat clients
  • Easy ETL and options for persistence by data import / manipulation / export of several formats
  • All major browsers, Node.js, and mobile applications

We focus on speed by taking advantage of the dynamic nature of JavaScript when building up queries. Real-world solutions demand flexibility regarding where data comes from and where it is to be stored. We focus on flexibility by making sure you can import/export and query directly on data stored in Excel (both .xls and .xlsx), CSV, JSON, TAB, IndexedDB, LocalStorage, and SQLite files.

The library adds the comfort of a full database engine to your JavaScript app. No, really - it's working towards a full database engine complying with most of the SQL-99 language, spiced up with additional syntax for NoSQL (schema-less) data and graph networks.

Traditional SQL Table

/* create SQL Table and add data */
alasql("CREATE TABLE cities (city string, pop number)");

alasql("INSERT INTO cities VALUES ('Paris',2249975),('Berlin',3517424),('Madrid',3041579)");

/* execute query */
var res = alasql("SELECT * FROM cities WHERE pop < 3500000 ORDER BY pop DESC");

// res = [ { "city": "Madrid", "pop": 3041579 }, { "city": "Paris", "pop": 2249975 } ]

Live Demo

Array of Objects

var data = [ {a: 1, b: 10}, {a: 2, b: 20}, {a: 1, b: 30} ];

var res = alasql('SELECT a, SUM(b) AS b FROM ? GROUP BY a',[data]);

// res = [ { "a": 1, "b": 40},{ "a": 2, "b": 20 } ]

Live Demo

Spreadsheet

// file is read asynchronously (Promise returned when SQL given as array)
alasql(['SELECT * FROM XLS("./data/mydata") WHERE lastname LIKE "A%" and city = "London" GROUP BY name '])
    .then(function(res){
        console.log(res); // output depends on mydata.xls
    }).catch(function(err){
        console.log('Does the file exist? There was an error:', err);
    });

Bulk Data Load

alasql("CREATE TABLE example1 (a INT, b INT)");

// alasql's data store for a table can be assigned directly
alasql.tables.example1.data = [
    {a:2,b:6},
    {a:3,b:4}
];

// ... or manipulated with normal SQL
alasql("INSERT INTO example1 VALUES (1,5)");

var res = alasql("SELECT * FROM example1 ORDER BY b DESC");

console.log(res); // [{a:2,b:6},{a:1,b:5},{a:3,b:4}]

If you are familiar with SQL, it should be no surprise that proper use of indexes on your tables is essential for good performance.

Options

AlaSQL has several configuration options which change the behavior. It can be set via SQL statements or via the options object before using alasql.

If you're using NOW() in queries often, setting alasql.options.dateAsString to false speed things up. It will just return a JS Date object instead of a string representation of a date.

Installation

yarn add alasql                # yarn

npm install alasql             # npm

npm install -g alasql          # global install of command line tool

For the browsers: include alasql.min.js

<script src="https://cdn.jsdelivr.net/npm/alasql@4"></script>

Getting started

See the "Getting started" section of the wiki

More advanced topics are covered in other wiki sections like "Data manipulation" and in questions on Stack Overflow

Other links:

Please note

All contributions are extremely welcome and greatly appreciated(!) - The project has never received any funding and is based on unpaid voluntary work: We really (really) love pull requests

The AlaSQL project depends on your contribution of code and may have bugs. So please, submit any bugs and suggestions as an issue.

Please check out the limitations of the library.

Performance

AlaSQL is designed for speed and includes some of the classic SQL engine optimizations:

  • Queries are cached as compiled functions
  • Joined tables are pre-indexed
  • WHERE expressions are pre-filtered for joins

See more performance-related info on the wiki

Features you might like

Traditional SQL

Use "good old" SQL on your data with multiple levels of: JOIN, VIEW, GROUP BY, UNION, PRIMARY KEY, ANY, ALL, IN, ROLLUP(), CUBE(), GROUPING SETS(), CROSS APPLY, OUTER APPLY, WITH SELECT, and subqueries. The wiki lists supported SQL statements and keywords.

User-Defined Functions in your SQL

You can use all benefits of SQL and JavaScript together by defining your own custom functions. Just add new functions to the alasql.fn object:

alasql.fn.myfn = function(a,b) {
    return a*b+1;
};
var res = alasql('SELECT myfn(a,b) FROM one');

You can also define your own aggregator functions (like your own SUM(...)). See more in the wiki

Compiled statements and functions

var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);

See more in the wiki

SELECT against your JavaScript data

Group your JavaScript array of objects by field and count number of records in each group:

var data = [{a:1,b:1,c:1},{a:1,b:2,c:1},{a:1,b:3,c:1}, {a:2,b:1,c:1}];
var res = alasql('SELECT a, COUNT(*) AS b FROM ? GROUP BY a', [data] );

See more ideas for creative data manipulation in the wiki

JavaScript Sugar

AlaSQL extends "good old" SQL to make it closer to JavaScript. The "sugar" includes:

  • Write Json objects - {a:'1',b:@['1','2','3']}

  • Access object properties - obj->property->subproperty

  • Access object and arrays elements - obj->(a*1)

  • Access JavaScript functions - obj->valueOf()

  • Format query output with SELECT VALUE, ROW, COLUMN, MATRIX

  • ES5 multiline SQL with var SQL = function(){/*SELECT 'MY MULTILINE SQL'*/} and pass instead of SQL string (will not work if you compress your code)

Read and write Excel and raw data files

You can import from and export to CSV, TAB, TXT, and JSON files. File extensions can be omitted. Calls to files will always be asynchronous so multi-file queries should be chained:

var tabFile = 'mydata.tab';

alasql.promise([
    "SELECT * FROM txt('MyFile.log') WHERE [0] LIKE 'M%'", // parameter-less query
    [ "SELECT * FROM tab(?) ORDER BY [1]", [tabFile] ],    // [query, array of params]
    "SELECT [3] AS city,[4] AS population FROM csv('./data/cities')",
    "SELECT * FROM json('../config/myJsonfile')"
]).then(function(results){
    console.log(results);
}).catch(console.error);

Read SQLite database files

AlaSQL can read (but not write) SQLite data files using SQL.js library:

<script src="alasql.js"></script>
<script src="sql.js"></script>
<script>
    alasql([
        'ATTACH SQLITE DATABASE Chinook("Chinook_Sqlite.sqlite")',
        'USE Chinook',
        'SELECT * FROM Genre'
    ]).then(function(res){
        console.log("Genres:",res.pop());
    });
</script>

sql.js calls will always be asynchronous.

AlaSQL works in the console - CLI

The node module ships with an alasql command-line tool:

$ npm install -g alasql ## install the module globally

$ alasql -h ## shows usage information

$ alasql "SET @data = @[{a:'1',b:?},{a:'2',b:?}]; SELECT a, b FROM @data;" 10 20
[ 1, [ { a: 1, b: 10 }, { a: 2, b: 20 } ] ]

$ alasql "VALUE OF SELECT COUNT(*) AS abc FROM TXT('README.md') WHERE LENGTH([0]) > ?" 140
// Number of lines with more than 140 characters in README.md

More examples are included in the wiki

Features you might love

AlaSQL ♥ D3.js

AlaSQL plays nice with d3.js and gives you a convenient way to integrate a specific subset of your data with the visual powers of D3. See more about D3.js and AlaSQL in the wiki

AlaSQL ♥ Excel

AlaSQL can export data to both Excel 2003 (.xls) and Excel 2007 (.xlsx) formats with coloring of cells and other Excel formatting functions.

AlaSQL ♥ Meteor

Meteor is amazing. You can query directly on your Meteor collections with SQL - simple and easy. See more about Meteor and AlaSQL in the wiki

AlaSQL ♥ Angular.js

Angular is great. In addition to normal data manipulation, AlaSQL works like a charm for exporting your present scope to Excel. See more about Angular and AlaSQL in the wiki

AlaSQL ♥ Google Maps

Pinpointing data on a map should be easy. AlaSQL is great to prepare source data for Google Maps from, for example, Excel or CSV, making it one unit of work for fetching and identifying what's relevant. See more about Google Maps and AlaSQL in the wiki

AlaSQL ♥ Google Spreadsheets

AlaSQL can query data directly from a Google spreadsheet. A good "partnership" for easy editing and powerful data manipulation. See more about Google Spreadsheets and AlaSQL in the wiki

Miss a feature?

Take charge and add your idea or vote for your favorite feature to be implemented:

Feature Requests

Limitations

Please be aware that AlaSQL has bugs. Beside having some bugs, there are a number of limitations:

  1. AlaSQL has a (long) list of keywords that must be escaped if used for column names. When selecting a field named key please write SELECT `key` FROM ... instead. This is also the case for words like `value`, `read`, `count`, `by`, `top`, `path`, `deleted`, `work` and `offset`. Please consult the full list of keywords.

  2. It is OK to SELECT 1000000 records or to JOIN two tables with 10000 records in each (You can use streaming functions to work with longer datasources - see test/test143.js) but be aware that the workload is multiplied so SELECTing from more than 8 tables with just 100 rows in each will show bad performance. This is one of our top priorities to make better.

  3. Limited functionality for transactions (supports only for localStorage) - Sorry, transactions are limited, because AlaSQL switched to more complex approach for handling PRIMARY KEYs / FOREIGN KEYs. Transactions will be fully turned on again in a future version.

  4. A (FULL) OUTER JOIN and RIGHT JOIN of more than 2 tables will not produce expected results. INNER JOIN and LEFT JOIN are OK.

  5. Please use aliases when you want fields with the same name from different tables (SELECT a.id AS a_id, b.id AS b_id FROM ?).

  6. At the moment AlaSQL does not work with JSZip 3.0.0 - please use version 2.x.

  7. JOINing a sub-SELECT does not work. Please use a with structure (Example here) or fetch the sub-SELECT to a variable and pass it as an argument (Example here).

  8. AlaSQL uses the FileSaver.js library for saving files locally from the browser. Please be aware that it does not save files in Safari 8.0.

There are probably many others. Please help us fix them by submitting an issue. Thank you!

How To

Use AlaSQL to convert data from CSV to Excel

ETL example:

alasql([
    'CREATE TABLE IF NOT EXISTS geo.country',
    'SELECT * INTO geo.country FROM CSV("country.csv",{headers:true})',
    'SELECT * INTO XLSX("asia") FROM geo.country WHERE continent_name = "Asia"'
]).then(function(res){
    // results from the file asia.xlsx
});

Use AlaSQL as a Web Worker

AlaSQL can run in a Web Worker. Please be aware that all interaction with AlaSQL when running must be async.

From the browser thread, the browser build alasql-worker.min.js automagically uses Web Workers:

<script src="alasql-worker.min.js"></script>
<script>
var arr = [{a:1},{a:2},{a:1}];

alasql([['SELECT * FROM ?',[arr]]]).then(function(data){
    console.log(data);
});
</script>

Live Demo.

The standard build alasql.min.js will use Web Workers if alasql.worker() is called:

<script src="alasql.min.js"></script>
<script>
alasql.worker();
alasql(['SELECT VALUE 10']).then(function(res){
    console.log(res);
}).catch(console.error);
</script>

Live Demo.

From a Web Worker, you can import alasql.min.js with importScripts:

importScripts('alasql.min.js');

Webpack, Browserify, Vue and React (Native)

When targeting the browser, several code bundlers like Webpack and Browserify will pick up modules you might not want.

Here's a list of modules that AlaSQL may require in certain environments or for certain features:

  • Node.js
    • fs
    • net
    • tls
    • request
    • path
  • React Native
    • react-native
    • react-native-fs
    • react-native-fetch-blob
  • Vertx
    • vertx
  • Agonostic
    • XLSX/XLS support
      • cptable
      • jszip
      • xlsx
      • cpexcel
    • es6-promise

Webpack

There are several ways to handle AlaSQL with Webpack:

IgnorePlugin

Ideal when you want to control which modules you want to import.

var IgnorePlugin =  require("webpack").IgnorePlugin;

module.exports = {
  ...
  // Will ignore the modules fs, path, xlsx, request, vertx, and react-native modules
  plugins:[new IgnorePlugin(/(^fs$|cptable|jszip|xlsx|^es6-promise$|^net$|^tls$|^forever-agent$|^tough-cookie$|cpexcel|^path$|^request$|react-native|^vertx$)/)]
};
module.noParse

As of AlaSQL 0.3.5, you can simply tell Webpack not to parse AlaSQL, which avoids all the dynamic require warnings and avoids using eval/clashing with CSP with script-loader. Read the Webpack docs about noParse

...
//Don't parse alasql
{module:noParse:[/alasql/]}
script-loader

If both of the solutions above fail to meet your requirements, you can load AlaSQL with script-loader.

//Load alasql in the global scope with script-loader
import "script!alasql"

This can cause issues if you have a CSP that doesn't allow eval.

Browserify

Read up on excluding, ignoring, and shimming

Example (using excluding)

var browserify = require("browserify");
var b = browserify("./main.js").bundle();
//Will ignore the modules fs, path, xlsx
["fs","path","xlsx",  ... ].forEach(ignore => { b.ignore(ignore) });

Vue

For some frameworks (lige Vue) alasql cant access XLSX by it self. We recommend handling it by including AlaSQL the following way:

import XLSX from 'xlsx';
alasql.utils.isBrowserify = false;
alasql.utils.global.XLSX = XLSX;

jQuery

Please remember to send the original event, and not the jQuery event, for elements. (Use event.originalEvent instead of myEvent)

JSON-object

You can use JSON objects in your databases (do not forget use == and !== operators for deep comparison of objects):

alasql> SELECT VALUE {a:'1',b:'2'}

{a:1,b:2}

alasql> SELECT VALUE {a:'1',b:'2'} == {a:'1',b:'2'}

true

alasql> SELECT VALUE {a:'1',b:'2'}->b

2

alasql> SELECT VALUE {a:'1',b:(2*2)}->b

4

Try AlaSQL JSON objects in Console [sample](http://alasql.org/console?drop table if exists one;create table one;insert into one values {a:@[1,2,3],c:{e:23}}, {a:@[{b:@[1,2,3]}]};select * from one)

Experimental

Useful stuff, but there might be dragons

Graphs

AlaSQL is a multi-paradigm database with support for graphs that can be searched or manipulated.

// Who loves lovers of Alice?
var res = alasql('SEARCH / ANY(>> >> #Alice) name');
console.log(res) // ['Olga','Helen']

See more in the wiki

localStorage and DOM-storage

You can use browser localStorage and DOM-storage as a data storage. Here is a sample:

alasql('CREATE localStorage DATABASE IF NOT EXISTS Atlas');
alasql('ATTACH localStorage DATABASE Atlas AS MyAtlas');
alasql('CREATE TABLE IF NOT EXISTS MyAtlas.City (city string, population number)');
alasql('SELECT * INTO MyAtlas.City FROM ?',[ [
        {city:'Vienna', population:1731000},
        {city:'Budapest', population:1728000}
] ]);
var res = alasql('SELECT * FROM MyAtlas.City');

Try this sample in jsFiddle. Run this sample two or three times, and AlaSQL store more and more data in localStorage. Here, "Atlas" is the name of localStorage database, where "MyAtlas" is a memory AlaSQL database.

You can use localStorage in two modes: SET AUTOCOMMIT ON to immediate save data to localStorage after each statement or SET AUTOCOMMIT OFF. In this case, you need to use COMMIT statement to save all data from in-memory mirror to localStorage.

Plugins

AlaSQL supports plugins. To install a plugin you need to use the REQUIRE statement. See more in the wiki

Alaserver - simple database server

Yes, you can even use AlaSQL as a very simple server for tests.

To run enter the command:

$ alaserver

then open http://127.0.0.1:1337/?SELECT%20VALUE%20(2*2) in your browser

Warning: Alaserver is not multi-threaded, not concurrent, and not secured.

Tests

Regression tests

AlaSQL currently has over 1200 regression tests, but they only cover Coverage of the codebase.

AlaSQL uses mocha for regression tests. Install mocha and run

$ npm test

or open test/index.html for in-browser tests (Please serve via localhost with, for example, http-server).

Tests with AlaSQL ASSERT from SQL

You can use AlaSQL's ASSERT operator to test the results of previous operation:

CREATE TABLE one (a INT);             ASSERT 1;
INSERT INTO one VALUES (1),(2),(3);   ASSERT 3;
SELECT * FROM one ORDER BY a DESC;    ASSERT [{a:3},{a:2},{a:1}];

SQLLOGICTEST

AlaSQL uses SQLLOGICTEST to test its compatibility with SQL-99. The tests include about 2 million queries and statements.

The testruns can be found in the testlog.

Contributing

See Contributing for details.

Thanks to all the people who already contributed!

License

MIT - see MIT licence information

Main contributors

AlaSQL is an OPEN Open Source Project. This means that:

Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.

We appreciate any and all contributions we can get. If you feel like contributing, have a look at CONTRIBUTING.md

Credits

Many thanks to:

and other people for useful tools, which make our work much easier.

Related projects that have inspired us

  • AlaX - Export to Excel with colors and formats
  • AlaMDX - JavaScript MDX OLAP library (work in progress)
  • Other similar projects - list of databases on JavaScript

AlaSQL logo © 2014-2024, Andrey Gershun ([email protected]) & Mathias Rangel Wulff ([email protected])

See this article for a bit of information about the motivation and background.

node-red-contrib-alasql's People

Contributors

agershun avatar dependabot-preview[bot] avatar dependabot[bot] avatar iamgaborgithub avatar mathiasrw avatar renovate[bot] avatar riverrush avatar snyk-bot avatar tmdoit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-red-contrib-alasql's Issues

Please remove the node-red keyword

Hi there, could I please ask that you remove the node-red keyword from the package.json until this actually works? That will remove it from the flows listing and prevent people from having problems by installing it before it is ready.

Thanks.

Trying to query direct on a CSV file doesn't work if using payload as the filename

I have a query that works perfectly if I put it in the query window. But if I try to move the filename to msg.payload (using the inject node) and use either FROM ? or FROM $0, it doesn't work. There is no error but zero records are returned.

This works:

SELECT * 
FROM 'C:/Users/xxxxx/Staff List for COVID19 21Sep20.csv'
WHERE Employee_Last_Name = "Knight"

This does not (where msg.payload = 'C:/Users/xxxxx/Staff List for COVID19 21Sep20.csv') :

SELECT * 
FROM ?
WHERE Employee_Last_Name = "Knight"

Neither does this:

SELECT * 
FROM $0
WHERE Employee_Last_Name = "Knight"

This, however, does work (where msg.payload = 'Knight'):

SELECT * 
FROM 'C:/Users/xxxxx/Staff List for COVID19 21Sep20.csv'
WHERE Employee_Last_Name = $0

msg.topic doesn't work as predefined sql queries

Hi!

I find out that msg.topic is mentioned in the readMe of alasql node, but it isn't used in the code. A made a change on the code at my local. I changed in the readMe msg.topic to msg.query because msg.topic used bz several another nodes. And I changed the node-red-contrib-alasql.js line 9 from var sql = this.query || 'SELECT * FROM ?'; to var sql = this.query || msg.query || 'SELECT * FROM ?'; to use this variable. It works fine for me. Please let me know how can it be released?

Thank you very much, Gábor

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

node-red-contrib-alasql: JOIN DOESN'T WORK

Hi guys,
maybe someone of you can help me.

I'm working with AlaSQL wrapper for node-red, and it seems that JOIN condition doesn't work at all.

Let's start with something simple (from the examples):

  1. I have a first function-block set with this code:
var data = { COLORS: [[1,"red"],[2,"yellow"],[3,"orange"]], "FRUITS":[[1,"apple"],[2,"banana"],[3,"orange"]]}; 

msg.payload=[data.COLORS, data.FRUITS];

return msg;
  1. then I have AlaSQL block with the following query
    SELECT MATRIX COLORS.[0], COLORS.[1], FRUITS.[1] AS [2] FROM ? AS COLORS JOIN ? AS FRUITS USING [0]
  2. Then if I deploy the flow and execute it I get :

TypeError: Cannot read property 'length' of undefined

Does anyone of you have an example of a working join condition with AlaSQL in node-red ?

Here are the complete flow code

[{"id":"d8ea2581.c9eaa8","type":"alasql","z":"44bba25d.edd63c","name":"","query":"SELECT MATRIX COLORS.[0], COLORS.[1], FRUITS.[1] AS [2] FROM ? AS COLORS JOIN ? AS FRUITS USING [0]","x":910,"y":80,"wires":[["4e58c548.dcf80c"]]},{"id":"e1180ede.b9d41","type":"function","z":"44bba25d.edd63c","name":"","func":"var data = {COLORS: [[1,\"red\"],[2,\"yellow\"],[3,\"orange\"]],\"FRUITS\":[[1,\"apple\"],[2,\"banana\"],[3,\"orange\"]]};\n\nmsg.payload=[data.COLORS, data.FRUITS];\n\nreturn msg;","outputs":1,"noerr":0,"x":790,"y":80,"wires":[["d8ea2581.c9eaa8"]]},{"id":"4e58c548.dcf80c","type":"debug","z":"44bba25d.edd63c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":1030,"y":80,"wires":[]},{"id":"a887efce.c7898","type":"inject","z":"44bba25d.edd63c","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":660,"y":80,"wires":[["e1180ede.b9d41"]]}]

Outputs from Query Node

Is there a specific reason the query node has no outputs? It seems odd since you put the results of the query into the msg.payload. Maybe I am not quite understanding the intent of this node. We are looking to use the node inside a larger flow that is essentially performing ETL type functions.

Alafile out - overwrites target file

I'm not sure if this is a problem due to my lack of understanding of json and that stuff but here goes anyway.
I send an inventory of machines and their postcodes to a node called Postcode Lookup with the result that it returns the geographical coordinates of the machine from its postcode. This works fine and I now want to save the resulting list of positions ...
If I use the "file" node with the action "append to file" selected, I get a file with the machine listing showing id, latitude and longitude.
However, if I try to use Alafile out node (which is excellent btw!) , let's say to create a csv or an Excel file, I just get one record saved to the csv or xls file (I think it's the last machine in the list) which suggests that the node is overwriting rather than appending to the new file ... which is what I want. Have I missed something or is there an issue with my input to Alafile?

thanks!

Array parameters passed via msg.payload to alasql node not working

Array of parameters passed in msg.payload is treated by alasql in insert as one parameter, ie.:
[{"id":"c1a70029.98ea7","type":"alasql","z":"2d89d4b5.a581bc","name":"","query":"CREATE TABLE ArticleGroups (Code string, Name string);","x":250,"y":1120,"wires":[["67e913ab.e7446c"]]},{"id":"af2252b0.09bc6","type":"inject","z":"2d89d4b5.a581bc","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":100,"y":1120,"wires":[["c1a70029.98ea7"]]},{"id":"67e913ab.e7446c","type":"function","z":"2d89d4b5.a581bc","name":"","func":"msg.payload = [\"fd\",\"df\"];\nreturn msg;","outputs":1,"noerr":0,"x":400,"y":1120,"wires":[["23c7e6be.9f2bea"]]},{"id":"23c7e6be.9f2bea","type":"alasql","z":"2d89d4b5.a581bc","name":"","query":"INSERT INTO ArticleGroups VALUES (?,?);\nSELECT * FROM ArticleGroups;","x":550,"y":1120,"wires":[["d4e3b5c3.4e4e28","d43d6056.198fb"]]},{"id":"d4e3b5c3.4e4e28","type":"alasql","z":"2d89d4b5.a581bc","name":"","query":"DROP TABLE ArticleGroups;","x":710,"y":1120,"wires":[[]]},{"id":"d43d6056.198fb","type":"debug","z":"2d89d4b5.a581bc","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":700,"y":1060,"wires":[]}]

Proposed feature changes

Hi @agershun and @mathiasrw :)

Developers on my staff are interfacing to kiosk machines running node-red, with flows which publish mqtt topics to our main HQ. At HQ we are implementing node-red to continue the flow which updates our databases, ERP, and PIM systems. But since the HQ dev staff is more knowledgeable in SQL than JavaScript (we're getting there :) - your node-red-contrib-alasql nodes are the best thing since slice bread!

I have forked your repo and am in the process of implementing/testing the following changes to my fork of node-red-contrib-alasq within the next few weeks. I have other experiences and features of using alasql nodes 'in the wild' that you might be interested in for future consideration.

Your input would be greatly appreciated, and hopefully you might be interested pulling some of these changes into your repo if I were to submit a PR?

Functional updates

The core "file in" and "file out" node(s) info is :
The filename can be configured in the node. If left blank it should be set by msg.filename on the incoming message. Ala file in/out nodes should work similarly - thus works as a drop-in replacement for the core file in/out nodes.

  • ala file in/out - ability to pass name of in/out filename in msg.filename.

While building flows that use ala file in/out - it is handy to have the node-red editor inform devs that the payload contains data and the name of the file the data is read/output.

  • Check, display, and insure the filename and payload objects are defined upon node entry.

Cosmetic updates

The ala file out is shown before the ala file in node with-in the node-red palette - should be after ala file in.

  • Reorder in/out scripts in ala-file.html so ala file in displays before ala file out in the node-red editor palette.

Visually, the ala file out should have the alasql icon on the right side of the node display. By convention, nodes with with an input connector but no output connector (an output node) normally locates the icon on the right side of the node display.

  • Move the alasql icon in ala file out node from the left to the right side of the node display

Node background colors for file in/out in the node-red editor palette should be the same. The alasql node background (under advanced tab) to remain a slightly darker color to be visually different from the ala file nodes.

  • Make both ala file in/out nodes to the same background color.

During development, the node-red editor should display the filename of the file read or written.

  • Display a status message on the editor showing the filename ala file in/out read/wrote.

TIA for your consideration and advice!,

@PotOfCoffee2Go

Access NR global context inside function

I'm trying to use external moment.js lib without luck. Here is my code:

CREATE FUNCTION getWeek AS 
``
    function(x) { 
        let moment = global.get('moment');
        return moment(x).week();
    }
``;
SELECT 
    COUNT(*), 
    SUBSTRING(created_at,1,10) AS created_at,
    getWeek(created_at)
FROM ?
GROUP BY SUBSTRING(created_at,1,10)

I failed also when tried to acceess msg object. Is there a way to resolve it?

EDITED:
As a workaround I used moment in function node before using alasql node so I can work with "ready" data.

let moment = global.get('moment');
for (let i = 0; i < msg.payload.length; i++) {
    msg.payload[i].week = moment(msg.payload[i].created_at).week(),
    msg.payload[i].month = moment(msg.payload[i].created_at).month(),
    msg.payload[i].yaer = moment(msg.payload[i].created_at).year()
}
return msg;

UNION ALL problem

AlaSQL node is very good but I'm having difficulty performing a UNION ALL when I do a Select on two spreadsheets (or two sheets from one spreadsheet). Node-red crashes with an uncaught exception error ...
30 Aug 11:23:53 - [red] Uncaught Exception:
30 Aug 11:23:53 - TypeError: Cannot read property 'data' of undefined
at queryfn3 (C:\Users\IBM_ADMIN.node-red\node_modules\alasql\dist\alasql.fs.js:6401:11)
at queryfn2 (C:\Users\IBM_ADMIN.node-red\node_modules\alasql\dist\alasql.fs.js:6305:9)
at C:\Users\IBM_ADMIN.node-red\node_modules\alasql\dist\alasql.fs.js:15680:10
at C:\Users\IBM_ADMIN.node-red\node_modules\alasql\dist\alasql.fs.js:3591:21
at C:\Users\IBM_ADMIN.node-red\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:78:16
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:445:3)

I can read data from individual spreadsheets or tables but if I try the UNION it fails.
Here's my SQL from within the node..
select * from xlsx("c:\union.xlsx")
union all
select * from xlsx("c:\union2.xlsx")

These are small (2 lines) worksheets and are exactly the same format (NAME, SURNAME, ID)

"TypeError: Cannot read property 'toJS' of undefined"

I'm getting this error when trying run below query

CREATE TABLE t
(
    report_type string,
    inv_qty number,
    week number,
    month number,
    year number
);

INSERT INTO t(report_type,inv_qty,week,month,year) VALUES ((SELECT 'k',1,2,3,4));
SELECT * FROM t;

Using Buffer

Hello,

I have an xls format spreadsheet that I upload via dropbox.

The output of node is a buffer. It would be possible to use the buffer as input from node alafile in

NULL value is not returned in payload

SELECT NULL AS 'col1'

returns msg.payload:

[{}]

It's intended behavior?

EDITED:
As workaround I'm using empty string to not lost object properties.

Re-implement SQL output format

It is relatively easy in node-red to query relational databases (such as Oracle, MS, MySql) and update No-Sql databases (such as Mongo, Couch, Raven) . But the reverse is more difficult - inserting/updating data resulting from a No-Sql database to a relational database.

In the current release of node-red alasql, the SQL output format - 'INSERT INTO table_name VALUES (value1, value2, value3, ...);' was depreciated (by my request ;( ) due to requiring some significant mods to the alasql node to operate properly for the SQL output format.

AlaSql is perfect for that task. In the next few weeks I will be changing the alasql node to be able to query the results from No-Sql databases and produce the INSERT INTO statements required to update relational databases.

Any suggestions or comments appreciated!
@PotOfCoffee2Go

SELECT statement does not work properly

Hi,
When I tried to select from a json object, it didn't work properly.
Am I doing it wrong?
Sorry to trouble you, but please try the following flow.
version is 2.0.1

[{"id":"9710bc666e27f8ca","type":"alasql","z":"89cdb3c1eff17690","name":"SELECT","query":"-- SELECT * FROM ? WHERE age >= 17;\nSELECT * FROM ?","x":300,"y":1060,"wires":[["7dbd635df236fddb"]]},{"id":"7cec6519f9bab538","type":"inject","z":"89cdb3c1eff17690","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[{\"name\":\"ken\",\"age\":19},{\"name\":\"rei\",\"age\":18}]","payloadType":"json","x":130,"y":1060,"wires":[["9710bc666e27f8ca"]]},{"id":"7dbd635df236fddb","type":"debug","z":"89cdb3c1eff17690","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":490,"y":1060,"wires":[]}]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.