npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sql-filter

v0.0.10

Published

Create SQL filters from patterns

Downloads

2

Readme

SQL Filter

npm version Build Status Coverage Status

Create simple to complex SQL filters using glob-like patterns.

Dislaimer

This module is still in development, and the first major version should be released soon! While the generated queries should be optimal, more tests are required against various data types and structures.

Install

npm i sql-filter --save

Database Adapters

  • PostreSQL
  • MySQL (Not implemented. Contribution welcome!)
  • more?

Usage

const builder = require('sql-filter');

const filterOptions = {
  // build a PostreSQL query (this is the default value)
  adapter: 'postgresql',
  // when no operator is specified, use this operator
  // (this is the default value)
  operator: '='
};

const userSearchFilter = builder('{ username, first_name, last_name }', filterOptions);
const inventorySearchFilter = builder('properties[].{ name(ILIKE,1), value(>=,2) }', filterOptions);

// userSearchFilter.toString()
// -> 'username = @1 OR first_name = @1 OR last_name = @1'
// inventorySearchFilter.toString()
// -> 'properties IS NOT NULL AND EXISTS (SELECT * FROM json_array_elements(properties) AS _properties WHERE _properties->>\'name\' ILIKE @1::TEXT OR _properties->>\'value\' >= @2::TEXT)'

let query1 = db.query('SELECT * FROM users WHERE ' + userSearchFilter.apply('John'));
query1.on('row', function (row) {
  console.log('* User', row);
});

let query2 = db.query('SELECT * FROM inventory_vw WHERE ' + inventorySearchFilter.apply('%pvc%', 3))
query2.on('row', function (row) {
  console.log('* Inventory', row);
});

NOTE: this module does not guarantee that the given fields exists, and only help generating queries.

Syntax

fields

Fields, or column names, are represented as is. For example, generating a filter to search for a given user :

const userById = builder('id');
const query = 'SELECT * FROM users' +
              ' WHERE ' + userById.apply(123);

Naturally, filters may be re-used.

const userById = builder('id');
const query = 'SELECT * FROM users' +
              ' WHERE ' + userById.apply(123) +
                 ' OR ' + userById.apply(456);

When aggregating data across tables, using functions to return JSON data types, or even when a table needs to filter from a JSON column type, searching deep within these structures may be combersome otherwise.

const issuesByOwner = builder('user.username');
// fetch from a VIEW which aggregates from users
const query = 'SELECT * FROM issues_vw' +
              ' WHERE ' + issuesByOwner.apply('[email protected]');

Arrays

Like for fields, arrays allow looking inside an enumeration. Useful when searching JSON arrays.

const recipesByIngredient = builder('ingredients[].name');
const query = 'SELECT * FROM recipees' +
              ' WHERE ' + recipesByIngredient.apply('avocado');

Arrays can be nested just fine, too!

const recipesByIngregidentsInStep = builder('steps[].ingredients[].name');
const query = 'SELECT * FROM recipees' +
              ' WHERE ' + recipesByIngregidentsInStep.apply('avocado');

Branching

Instead of repeating patterns, why not specify everything into a single one?

// search username OR first_name OR last_name
const userByStringOR = builder('{username,first_name,last_name}');
const queryOR = 'SELECT * FROM users' +
                ' WHERE ' + userByStringOR.apply('Bob');
// search username AND first_name AND last_name
const userByStringAND = builder('{{username,first_name,last_name}}');
const queryAND = 'SELECT * FROM users ' +
                 ' WHERE ' + userByStringAND.apply('Joe');

Field Operator

By default, field operators may be specified as an option argument of the builder function.

const filter = builder('a', { operator: 'LIKE'});
const query = 'SELECT * FROM tbl WHERE ' + filter.apply('%foo%');

Or it may be specified directly in the pattern.

const filter = builder('a(LIKE)');
const query = 'SELECT * FROM tbl WHERE ' + filter.apply('%foo%');

Field Arguments

To supply more than one values in the filter, the value order may be specified after specifying an operator.

const filter = builder('{{username(LIKE,1),status(=,2)}}');
const query = 'SELECT * FROM users WHERE ' + filter.apply('%john%', true);

BUilder options

Adapter

TODO

Default Operator

TODO

Field Name wrapper

TODO

Value wrapper

TODO

Adapters

Custom Operator Management

For complex filters, where built-in operators are simply not enough, it may be required to register a new one, to evaluate fields in a customized way. For example :

const adapter = require('sql-filter/adapter/postgresql');

adapter.registerOperatorHandler('custom', function (field, oper, args, argSuffix, options) {
  return 'customFunction(' + options.fieldWrapper(field) + ',' + args.map(options.valueWrapper).join(',') + ') = true';
});

Note: when an operator follows the pattern predicate operator predicate, it is not necessary to register a new handler as the default handler will correctly display any such operator.

Contribution

All contributions welcome! Every PR must be accompanied by their associated unit tests!

License

The MIT License (MIT)

Copyright (c) 2015 Mind2Soft [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.