Package: rbql
RBQL is an eval-based SQL-like query engine for (not only) CSV file processing. It provides SQL-like language that supports SELECT queries with Python expressions.RBQL is best suited for data transformation, data cleaning, and analytical queries.Official SiteUsing RBQL as a Python libraryIf you want to use rbql module as a python library for your own app - please readAPI DocumentationThe rbql module includes functions to query csv tables, pandas dataframes, python lists and more.Using RBQL as IPython "magic" commandSyntax%rbql <query>Usage examplefrom vega_datasets import data
my_cars = data.cars()
%load_ext rbql
result_df = %rbql SELECT a.Name, a.Weight_in_lbs / 1000, a.Horsepower FROM my_cars WHERE a.Horsepower > 100 ORDER BY a.Weight_in_lbs DESC LIMIT 15
result_dfYou can also visit thedemo Google Colab notebookto try the%rbql"magic" command.Using RBQL as a CLI AppInstallation:$ pip install rbqlUsage example (non-interactive mode):$ rbql-py --query "select a1, a2 order by a1" --delim , < input.csvUsage example (interactive mode):In interactive mode rbql-py will show input table preview so it is easier to type SQL-like query.$ rbql-py --input input.csv --output result.csvMain FeaturesUse Python expressions insideSELECT,UPDATE,WHEREandORDER BYstatementsSupports multiple input formatsResult set of any query immediately becomes a first-class table on its ownNo need to provide FROM statement in the query - input table is defined by the current contextSupports all main SQL keywordsSupports aggregate functions and GROUP BY queriesSupports user-defined functions (UDF)Provides some new useful query modes which traditional SQL engines do not haveLightweight, dependency-free, works out of the boxLimitations:RBQL doesn't support nested queries, but they can be emulated with consecutive queriesNumber of tables in all JOIN queries is always 2 (input table and join table), use consecutive queries to join 3 or more tablesSupported SQL Keywords (Keywords are case insensitive)SELECTUPDATEWHEREORDER BY ... [ DESC | ASC ][ LEFT | INNER ] JOINDISTINCTGROUP BYTOPNLIMITNASAll keywords have the same meaning as in SQL queries. You can check themonlineRBQL variablesRBQL for CSV files provides the following variables which you can use in your queries:a1,a2,...,a{N}Variable type:stringDescription: value of i-th field in the current record in input tableb1,b2,...,b{N}Variable type:stringDescription: value of i-th field in the current record in join table BNRVariable type:integerDescription: Record number (1-based)NFVariable type:integerDescription: Number of fields in the current recorda.name,b.Person_age, ...a.{Good_alphanumeric_column_name}Variable type:stringDescription: Value of the field referenced by it's "name". You can use this notation if the field in the header has a "good" alphanumeric namea["object id"],a['9.12341234'],b["%$ !! 10 20"]...a["Arbitrary column name!"]Variable type:stringDescription: Value of the field referenced by it's "name". You can use this notation to reference fields by arbitrary values in the headerUPDATE statementUPDATEquery produces a new table where original values are replaced according to the UPDATE expression, so it can also be considered a special type of SELECT query.Aggregate functions and queriesRBQL supports the following aggregate functions, which can also be used withGROUP BYkeyword:COUNT,ARRAY_AGG,MIN,MAX,SUM,AVG,VARIANCE,MEDIANLimitation: aggregate functions inside Python expressions are not supported. Although you can use expressions inside aggregate functions.E.g.MAX(float(a1) / 1000)- valid;MAX(a1) / 1000- invalid.There is a workaround for the limitation above forARRAY_AGGfunction which supports an optional parameter - a callback function that can do something with the aggregated array. Example:SELECT a2, ARRAY_AGG(a1, lambda v: sorted(v)[:5]) GROUP BY a2- Python;SELECT a2, ARRAY_AGG(a1, v => v.sort().slice(0, 5)) GROUP BY a2- JSJOIN statementsJoin table B can be referenced either by its file path or by its name - an arbitrary string which the user should provide before executing the JOIN query.RBQL supportsSTRICT LEFT JOINwhich is likeLEFT JOIN, but generates an error if any key in the left table "A" doesn't have exactly one matching key in the right table "B".Table B path can be either relative to the working dir, relative to the main table or absolute.Limitation:JOINstatements can't contain Python/JS expressions and must have the following form:<JOIN_KEYWORD> (/path/to/table.tsv | table_name ) ON a... == b... [AND a... == b... [AND ... ]]SELECT EXCEPT statementSELECT EXCEPT can be used to select everything except specific columns. E.g. to select everything but columns 2 and 4, run:SELECT * EXCEPT a2, a4Traditional SQL engines do not support this query mode.UNNEST() operatorUNNEST(list) takes a list/array as an argument and repeats the output record multiple times - one time for each value from the list argument.Example:SELECT a1, UNNEST(a2.split(';'))LIKE() functionRBQL does not support LIKE operator, instead it provides "like()" function which can be used like this:SELECT * where like(a1, 'foo%bar')WITH (header) and WITH (noheader) statementsYou can set whether the input (and join) CSV file has a header or not using the environment configuration parameters which could be--with_headersCLI flag or GUI checkbox or something else.
But it is also possible to override this selection directly in the query by adding eitherWITH (header)orWITH (noheader)statement at the end of the query.
Example:select top 5 NR, * with (header)User Defined Functions (UDF)RBQL supports User Defined FunctionsYou can define custom functions and/or import libraries in a special file:~/.rbql_init_source.py- for PythonExamples of RBQL queriesWith Python expressionsSELECT TOP 100 a1, int(a2) * 10, len(a4) WHERE a1 == "Buy" ORDER BY int(a2) DESCSELECT a.id, a.weight / 1000 AS weight_kgSELECT * ORDER BY random.random()- random sortSELECT len(a.vehicle_price) / 10, a2 WHERE int(a.vehicle_price) < 500 and a['Vehicle type'] in ["car", "plane", "boat"] limit 20- referencing columns by names from header and using Python's "in" to emulate SQL's "in"UPDATE SET a3 = 'NPC' WHERE a3.find('Non-playable character') != -1SELECT NR, *- enumerate records, NR is 1-basedSELECT * WHERE re.match(".*ab.*", a1) is not None- select entries where first column has "ab" patternSELECT a1, b1, b2 INNER JOIN ./countries.txt ON a2 == b1 ORDER BY a1, a3- example of join querySELECT MAX(a1), MIN(a1) WHERE a.Name != 'John' GROUP BY a2, a3- example of aggregate querySELECT *a1.split(':')- Using Python3 unpack operator to split one column into many. Do not try this with other SQL engines!RBQL design principles and architectureRBQL core idea is based on dynamic code generation and execution withexecandevalfunctions.
Here are the main steps that RBQL engine performs when processing a query:Shallow parsing: split the query into logical expressions such as "SELECT", "WHERE", "ORDER BY", etc.Embed the expression segments into the main loop template codeExecute the hydrated loop codeHere you can find a very basic working script (only 15 lines of Python code) which implements this idea:mini_rbql.pyThe diagram below gives an overview of the main RBQL components and data flow:Advantages of RBQL over traditional SQL enginesProvides power and flexibility of general purpose Python and JS languages in relational expressions (including regexp, math, file system, json, xml, random and many other libraries that these languages provide)Can work with different data sources including CSV files, sqlite tables, native 2D arrays/lists (traditional SQL engines are usually tightly coupled with their databases)Result set of any query immediately becomes a first-class table on its ownSupports both TOP and LIMIT keywordsProvides additional NR (record number) variable which is especially useful for input sources where record order is well defined (such as CSV files)Supports input tables with inconsistent number of fields per recordAllows to generate result sets with variable number of fields per record e.g. by using split() function and unpack operator (Python) / destructuring assignment (JS)UPDATE is a special case of SELECT query - this prevents accidental data lossNo need to use FROM statement - the table name is defined by the context. This improves query typing speed and allows immediate autocomplete for variables inside SELECT statement (in traditional SQL engines autocomplete will not work until you write FROM statement, which goes after SELECT statement)SELECT, WHERE, ORDER BY, and other statements can be rearranged in any way you likeSupports EXCEPT statementProvides a fully-functional client-side browser demo applicationAlmost nonexistent entry barrier both for SQL users and JS/Python usersIntegration with popular text editors (VSCode, Vim, Sublime Text, Atom)Small, maintainable, dependency-free, eco-friendly and hackable code base: RBQL engine fits into a single file with less than 2000 LOCDisadvantages of RBQL compared to traditional SQL enginesNot suitable for transactional workloadRBQL doesn't support nested queries, but they can be emulated with consecutive queriesNumber of tables in all JOIN queries is always 2 (input table and join table), use consecutive queries to join 3 or more tablesDoes not support HAVING statementReferencesRBQL: Official Siterbql-js library and CLI App for Node.js -npmRainbow CSV extension with integrated RBQL inVisual Studio CodeRainbow CSV extension with integrated RBQL inVimRainbow CSV extension with integrated RBQL inSublime Text 3Rainbow CSV extension with integrated RBQL inAtom