Node Postgres insert multiple rows based on array and static variable - sql

I am trying to insert multiple rows into a PostgresSQL server from my Nodejs server based on an array. I have a static variable, user_id, which would be the same for all entries but I want to change the filter_name based off an array. My goal is to not make multiple SQL insert calls.
arrayOfFilters = ["CM", "CBO", "SA", "EPS", "AD"]
await db.query(
"INSERT INTO filters(filter_name, requests_id)VALUES($1, $2)",
[arrayOfFiltersParams, user_id]);
I am hoping to have a row in the filters table for each one of the filters found in the arrayOfFilters with a matching user_id key for each entry (aka 5 rows for this example).
Thanks so much!

Write a helper function expand to build Parameterized query. Here is a solution:
import { pgclient } from '../../db';
function expand(rowCount, columnCount, startAt = 1) {
var index = startAt;
return Array(rowCount)
.fill(0)
.map(
(v) =>
`(${Array(columnCount)
.fill(0)
.map((v) => `$${index++}`)
.join(', ')})`,
)
.join(', ');
}
function flatten(arr) {
var newArr: any[] = [];
arr.forEach((v) => v.forEach((p) => newArr.push(p)));
return newArr;
}
(async function test() {
try {
await pgclient.connect();
// create table
await pgclient.query(`
CREATE TABLE IF NOT EXISTS filters (
id serial PRIMARY KEY,
filter_name VARCHAR(10),
requests_id INTEGER
)
`);
// test
const arrayOfFilters = ['CM', 'CBO', 'SA', 'EPS', 'AD'];
const user_id = 1;
const arrayOfFiltersParams: any[] = arrayOfFilters.map((el) => [el, user_id]);
await pgclient.query(
`INSERT INTO filters(filter_name, requests_id) VALUES ${expand(arrayOfFilters.length, 2)}`,
flatten(arrayOfFiltersParams),
);
} catch (error) {
console.log(error);
} finally {
pgclient.end();
}
})();
After executed above code, check the database:
node-sequelize-examples=# select * from "filters";
id | filter_name | requests_id
----+-------------+-------------
1 | CM | 1
2 | CBO | 1
3 | SA | 1
4 | EPS | 1
5 | AD | 1
(5 rows)

Related

Google Apps Script for BigQuery - different results of REGEXP_CONTAINS

I have troubles with my own SQL and REGEXP_CONTAINS, so I decided to test official BigQuery example from here. I used SQL from example, which shows how the REGEXP_CONTAINS works. See the SQL here:
SELECT
email,
REGEXP_CONTAINS(email, r'^([\w.+-]+#foo\.com|[\w.+-]+#bar\.org)$')
AS valid_email_address,
REGEXP_CONTAINS(email, r'^[\w.+-]+#foo\.com|[\w.+-]+#bar\.org$')
AS without_parentheses
FROM
(SELECT
['a#foo.com', 'a#foo.computer', 'b#bar.org', '!b#bar.org', 'c#buz.net']
AS addresses),
UNNEST(addresses) AS email;
+----------------+---------------------+---------------------+
| email | valid_email_address | without_parentheses |
+----------------+---------------------+---------------------+
| a#foo.com | true | true |
| a#foo.computer | false | true |
| b#bar.org | true | true |
| !b#bar.org | false | true |
| c#buz.net | false | false |
+----------------+---------------------+---------------------+
This SQL works as expected when I compose new query directly in BigQuery editor. But If I want to use SQL with the REGEXP_CONTAINS in Google Apps Script, then it doesn't work. The script I use is:
/**
* Runs a BigQuery query and logs the results in a spreadsheet.
*/
function testSQL() {
// Replace this value with the project ID listed in the Google
// Cloud Platform project.
var projectId = 'bigquery-xxxx';
var request = {
query: 'SELECT '+
'email, '+
'REGEXP_CONTAINS(email, r"^([\w.+-]+#foo\.com|[\w.+-]+#bar\.org)$")'+
' AS valid_email_address, '+
'REGEXP_CONTAINS(email, r"^[\w.+-]+#foo\.com|[\w.+-]+#bar\.org$")'+
' AS without_parentheses '+
'FROM'+
' (SELECT'+
' ["a#foo.com", "a#foo.computer", "b#bar.org", "!b#bar.org", "c#buz.net"]'+
' AS addresses),'+
' UNNEST(addresses) AS email;',
useLegacySql: false
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}
// Get all the rows of results.
var rows = queryResults.rows;
while (queryResults.pageToken) {
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
pageToken: queryResults.pageToken
});
rows = rows.concat(queryResults.rows);
}
if (rows) {
var spreadsheet = SpreadsheetApp.create('BiqQuery Results');
var sheet = spreadsheet.getActiveSheet();
// Append the headers.
var headers = queryResults.schema.fields.map(function(field) {
return field.name;
});
sheet.appendRow(headers);
// Append the results.
var data = new Array(rows.length);
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j] = cols[j].v;
}
}
sheet.getRange(2, 1, rows.length, headers.length).setValues(data);
Logger.log('Results spreadsheet created: %s',
spreadsheet.getUrl());
} else {
Logger.log('No rows returned.');
}
}
The script above creates the sheet and the results are:
What is wrong with REGEXP_CONTAINS?

Laravel Eloquent - Return unique values only and ignore all that appear more than once

I have 2 database tables.
|---------------------|------------------|
| Users | Matches |
|---------------------|------------------|
| user_id | match_id |
|---------------------|------------------|
| user_1 |
|------------------|
| user_2 |
|------------------|
with user_1 and user_2 being user_ids.
I am now trying to retrieve all matches with unique values only. As soon as a user ID is used twice, I don't want to retrieve ANY matches containing the id.
Example:
MATCHES (match_id, user_1, user_2):
1, 1, 2
2, 1, 3
3, 4, 5
4, 6, 7
5, 7, 8
The query should return 3, 4, 5 ONLY, because it's the only match containing only unique user_ids.
How should I go about this? I've been trying an approach using ->distinct() but that doesn't work since it only removes duplicates but I want to kick other entries containing the values as well.
Simple and crude, not a query based solution, but will get you what you want.
public function strictlyUniqueMatches()
{
$matches = Matches::distinct()->get();
$present = [];
foreach ($matches as $idx => $match) {
if (!isset($present[$match->user_1])) {
$present[$match->user_1] = 0;
}
if (!isset($present[$match->user_2])) {
$present[$match->user_2] = 0;
}
$present[$match->user_1]++;
$present[$match->user_2]++;
}
return $matches->filter(function ($match) use ($present) {
if ($present[$match->user_1] > 1) {
return false;
}
if ($present[$match->user_2] > 1) {
return false;
}
return true;
});
}

How to check number exists in Firebase Database? - react-native-firebase

I use react native through firebase database
I have a database creating products each product has a number
I want to take a number and compare it with the product number
And if there is then I want to get a product
the function its give me my correct name but where i use it on render its not found the variable (name)
getAllContact = async key => {
let barCodeData2 = this.props.navigation.state.params.barcodeData
let self = this;
let contactRef = firebase.database().ref()
contactRef.on("value", dataSnapsot => {
if (dataSnapsot.val()) {
let contactResult = Object.values(dataSnapsot.val())
let contactKey = Object.keys(dataSnapsot.val())
contactKey.forEach((value, key) => {
contactResult[key]["key"] = value
})
self.setState({
fname: contactResult.fname,
data: contactResult.sort((a, b) => {
var nameA = a.barcode
var nameB = barCodeData2
const name = a.fname
console.log(`${nameA} What numers issssssss`);
if (nameA == nameB) {
alert(`${name} ........`)
console.log(`${nameA == nameB}is Equqlqlqlql`);
return name
}
}),
})
}
})
}
render() {
let t=this.state.name
alert(`${t} how?`)// is give Not found
// let d = this.props.navigation.state.params.barcodeData
return (
)
}
When you try such a comparison query i.e.
let ref = firebase.firestore();
ref.collection('zoo')
.where("id", "==", myID)
.get()
.then((snapshot) => {
console.log(snap.empty); //this will denote if results are empty
snapshot.forEach(snap => {
console.log(snap.exists); //alternatively this will also tell you if it is empty
})
})
well what you can do is run query based on you product no and if there's a product you will a product if there's none you will get an empty array.
read firebase documentation on queries
https://firebase.google.com/docs/reference/js/firebase.database.Query

dojo 1.8: populate select box with items from database including null values

Hi I just want to populate the select or comboBox.
I am able to populate both with the searchAttr to any string from JSON. But not so when there are null values.
JSON string :
[{"batch":"0000001000"},{"batch":"0000"},{"batch":""},{"batch":null}]
dojo code:
var selBatch = new ComboBox //located at the left side of the page and it is the second select box in a row
(
{ id:'ID_selBatch',
value:'',
searchAttr:'batch',
placeHolder:'Select...',
style:{width:'150px'},
}, 'node_selBatch'
);
on(selTest, 'change', function(valueCard)
{
var selectedTest = this.get('displayedValue');
var selBatch = registry.byId('ID_selBatch');
console.debug('Connecting to gatherbatches.php ...');
request.post('gatherbatches.php',
{ data:{nameDB:registry.byId('ID_selPCBA').value, nameCard : valueCard},
handleAs: "json"}).then
(
function(response)
{
var memoStore2 = new Memory({data:response});
selBatch.set('store', memoStore2);
selBatch.set('value','');
console.debug('List of batches per Test is completed! Good OK! ');
},
function(error)
{
alert("Batch's Error:"+error);
console.debug('Problem: Listing batches per Test in select Test is BAD!');
}
);
selBatch.startup();
});
Error :
TypeError: _32[this.searchAttr] is null
defer() -> _WidgetBase.js (line 331)
_3() -> dojo.js (line 15)
_f.hitch(this,fcn)(); -> _WidgetBase.js (line 331)
Please advise though it might strange to have null values populate in the select box but these null values are related to data in other columns in database, so the null values included so that I can apply mysql scripts later. Or do you have other better suggestion?
Clement
You can create a QueryFilter as in this jsfiddle to achieve what you want, but it might be simpler to have two data items. Your original model with possibly null batch properties, and the model you pass to the store which is used by the ComboBox.
But anyway, this can work:
function createQueryFilter(originalQuery, filter) {
return function () {
var originalResults = originalQuery.apply(this, arguments);
var results = originalResults.filter(filter);
return QueryResults(results);
};
}
and
var memoStore = new Memory({
data: data
});
memoStore.query = createQueryFilter(memoStore.query, function (item) {
console.log(item);
return !!item.batch;
});
and the dummy data:
function createData1() {
var data = [];
for (var i = 0; i < 10; i++) {
data.push({
name: "" + i,
batch: (0 === i % 2) ? "batch" + i : null
});
}
return data;
}
Screenshot. The odd numbered batch items are null in my example.

SQL Query to show login count for each user in Wordpress

I would like a query that displays the number of times each user has logged in to Wordpress. The result would be something like:
User | Login_count
------------------
user1 | 2
------------------
user2 | 5
------------------
user3 | 0
etc..
Any ideas?
This should help get you started:
add_action('wp_login', 'db_increment');
function db_increment($login)
{
....
}
Is better to use update_user_meta instead create separate SQL queries to achieve such a simple functionality.
Code (functions.php) for that will looks like:
function my_handle_login($username, $user) {
$login_count = intval(get_user_meta($user->ID, 'user_count', true));
$login_count++;
update_user_meta($user->ID, 'user_count', $login_count);
}
add_action('wp_login', 'my_handle_login', 10, 2);
function new_modify_user_table( $column ) {
$column['counter'] = 'Logins Count';
return $column;
}
add_filter( 'manage_users_columns', 'new_modify_user_table' );
function new_modify_user_table_row( $val, $column_name, $user_id ) {
$user = get_userdata( $user_id );
switch ($column_name) {
case 'counter' :
return get_the_author_meta( 'user_count', $user_id );
break;
default:
}
return $return;
}
add_filter( 'manage_users_custom_column', 'new_modify_user_table_row', 10, 3 );