Currently, I'm connecting to database and creating tables with Sequelize, and doing the rest with Graphql, making the schemas, queries and resolvers.
I seem to have hit a wall with how to ask for the data from these 3 linked tables:
CITY CompLocations CompIssue
| id | | locationID | compID | | locationID | issueLevel |
|*1* | -----> | 1 | 45 | ------> | 45 | *5*
| 2 | | 2 | 203 | | 203 | 3
I just need to retrieve all the CompIssue.issueLevel's associated with CITY.id, via this existing relation/association.
Im looking at associations and querying in Sequelize's API. How would one query the above within a Grapql/Apollo resolver function?
I know this is an older question but I hit on a similar issue recently. In my case I am using seriate to connect to an MSSQL server from Nodejs and wanted to create the GraphQL schema dynamically based on the DB design (following the linked fields and such to create the sub-queries). Going this route I got the sql:
`SELECT
BASE_TABLE = t.TABLE_NAME,
BASE_COLUMN = col.COLUMN_NAME,
DATA_TYPE,
LEN_PRECISION = COALESCE(
CHARACTER_MAXIMUM_LENGTH,
numeric_precision,
datetime_precision
),
LINKED_TABLE = keys.Data_Table,
LINKED_COLUMN = keys.Data_Column
FROM INFORMATION_SCHEMA.TABLES t INNER JOIN
INFORMATION_SCHEMA.COLUMNS col ON
t.TABLE_NAME = col.TABLE_NAME LEFT JOIN
( SELECT
Base_Table = FK.TABLE_NAME,
Base_Column = CU.COLUMN_NAME,
Data_Table = PK.TABLE_NAME,
Data_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON
C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON
C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON
C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN
( SELECT
i1.TABLE_NAME,
i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON
i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON
PT.TABLE_NAME = PK.TABLE_NAME
) keys ON
keys.Base_Table = t.TABLE_NAME AND
keys.Base_Column = col.COLUMN_NAME
WHERE t.TABLE_TYPE = 'BASE TABLE'`
This may not be the most elegant, and is likely to hit some performance issues on larger databases, but it worked well for me. The final dataset will give you the list of table/column pairs with any links to other table/column pairs from your database design.
From this dataset it should be "trivial" to check for the links and create any sub-queries you need in your GraphQL setup.
Related
I have a table with DBName, SCName, Number. I wrote a procedure that inserts the DBName, SCName into the table and deletes a row when a Number is 0. I used merge to avoid duplicates and insert based on the condition but I don't understand how to delete a row when a Number=0.
------------------------
|DBName| SCName| Number|
| DB1 | SC1 | 1 |
| DB2 | SC2 | 0 | <-- Need to delete row
| DB2 | SC3 | 2 |
| DB2 | SC1 | 4 |
| DB3 | SC4 | 0 | <-- Need to delete row
------------------------
Here is my Procedure:
CREATE TABLE TABL(DBName VARCHAR, SCName VARCHAR); // creating table
CREATE OR REPLACE PROCEDURE repo(DB VARCHAR,SC VARCHAR)
RETURNS string
LANGUAGE JAVASCRIPT
AS
$$
//inserting values into table using merge
//if values are already present and Number = 0 then I need to delete row
var sql_command = `merge into TABL as t
using (SELECT :1 as database,:2 as schema) as s
on t.DBName = s.database
and t.SCName = s.schema
when matched then update
set t.DBName = t.DBName
when not matched then insert
(DBName, SCName) VALUES (:1,:2)`;
snowflake.execute({sqlText: sql_command, binds: [DB, SC]});
return 'success';
$$;
I didn't understand in which case (MATCHED / NOT MATCHED) the rows with '0' should be deleted from the target table.
But in general you have only can use DELETE in the MATCH-case:
when matched and number=0 then delete
It is important to avoid a nondeterministic result for the merge (see link below under "Duplicate Join Behavior"). Solution therefor is to also add "and number!=0" to your "when matched then update"-clause.
More infos: https://docs.snowflake.com/en/sql-reference/sql/merge.html
EDIT: I posted wrong information. For MATCH you can Delete and Update, for NOT MATCH you can INSERT.
I have two sheets with a dozen of columns and thousands of rows. Each sheet has a column A that contains a unique ID. I want to compare two sheets using only the column A as a point of comparison and generate a third sheet that contains entire rows with the unique ID that is in Sheet 1 but not in Sheet 2.
Here is a visualisation:
Sheet 1
+---+--------+-----+-----+
| | A | B | C |
+---+--------+-----+-----+
| 1 | 1111 | xxx | zzz |
| 2 | 2222 | yyy | zzz |
| 3 | 2222-1 | zzz | xxx |
| 4 | 3333 | xxx | yyy |
+---+--------+-----+-----+
Sheet 2
+---+------+-----+-----+
| | A | B | C |
+---+------+-----+-----+
| 1 | 1111 | xxx | zzz |
| 2 | 2222 | yyy | zzz |
| 3 | 3333 | xxx | yyy |
+---+------+-----+-----+
The desired function would compare Sheet 1 and Sheet 2 using A as the basis and the function would point out that the cell sheet1[A2] is unique, it would copy the entire 2:2 row, and then it would paste it into a newly generated sheet. The content of B and C is irrelevant in comparison.
I wanted to create a loop that would go and compare each cell in column A for both sheets and if sheet1.A[n] != sheet2.A[n], but it would work only if both sheets had the same lengths.
In the case I've specified above, the loop I've created with the help of the user Cooper finds that row 3 is unique and after that everything will be unique because of a misalignment.
The sheets will always be of different lengths and the uniques may appear at different spots (i.e. 2222-1 may end up the next time I'm making a comparison at row 5).
function compareSheetDrop(input) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
//establish first sheet and get its data range
var dropSheet = ss.getSheetByName("Drop (2)");
var dropRange = dropSheet.getRange(2, 1, dropSheet.getLastRow() - 1, dropSheet.getLastColumn());
var vA1 = dropRange.getValues();
//establish the sheet with new data and get its data range
var compareSheet = ss.getSheets()[4];
var compareRange = compareSheet.getRange(2, 1, compareSheet.getLastRow() - 1, compareSheet.getLastColumn());
var vA2 = compareRange.getValues();
//establish the sheet with results
var resultSheet = ss.getSheetByName("ADQA");
for (var i = 0; i < vA1.length; i++) {
//i've tried to make the loop stop once it encounters a blank cell to avoid a type error, but doesn't work
if (vA2[i][0] === '' || vA1[i][0] === '') {
break;
}
else if (vA1[i][0] != vA2[i][0]) {
Logger.log(vA1[i][0] + " & " + vA2[i][0]);
resultSheet.appendRow(vA2[i]);
}
}
}
Even if my code doesn't provide results I want, there are also two problems with it:
It loops until there's a TypeError: Cannot read property "0" from undefined. that I've tried to combat but to no avail.
Moreover, the appendRow method doesn't write data in already existing cells but inserts the row before the already existing ones - after running my test script 3 times the results sheet had thousands of columns and was barely operable.
Any ideas how I could modify my existing code to get what I want while avoiding the aforementioned issues? Or does it require a completely new approach? Any suggestions?
Flow:
Use Array#map to get all of sheet1 col A in a array(say a).
Use Array#filter to filter sheet2 by the array above.
Use the filtered array directly in setValues()
Snippet:
var a1 = [[1,'x','z'],[2,'y','z'],[3,'m','z'],['2-1','x','z']];//sheet1ValuesArr
var a2 = [[1,'x','z'],[2,'y','z'],[3,'m','z']];//Sheet2ValuesArr
var a = a2.map(function(e){ return e[0]}); //Sheet2Col A : [1,2,3]
var filteredArr = a1.filter(function(e){return !~a.indexOf(e[0])});
console.log(filteredArr); //to use in setValues
resultSheet.getRange(1, 1, filteredArr.length, filteredArr[0].length).setValues(filteredArr)
References:
Array#Filter
Range#setValues(array)
I am trying to create the following query with subqueries using Knex:
SELECT
t.*,
(SELECT COUNT(*) FROM team_users tu WHERE TeamID = t.ID) AS UserCount,
(SELECT COUNT(*) FROM team_access ta WHERE TeamID = t.ID) AS AppCount
FROM teams t WHERE OwnerUserID = _UserID;
The result should be the teams table with a count aggregation of UserCount and AppCount from different tables (team_users, team_access)
id | Name | OwnerUserID | UserCount | AppCount
-----------------------------------------------------
134| Team A | 1538 | 7 | 6
135| Team B | 1538 | 4 | 2
136| Team C | 1538 | 12 | 1
What I figured to be an equivalent knex implementation was:
var subquery1 = Knex.knex('team_users').count('*').where('TeamID', 'teams.ID').as('UserCount');
var subquery2 = Knex.knex('team_access').count('*').where('TeamID', 'teams.ID').as('AppCount');
Knex.knex.select('*', subquery1, subquery2).from('teams').where("OwnerUserID", ownerId).asCallback(dataSetCallback);
Running that, I do get the "UserCount" and "AppCount" columns in the returned object but always as zero, probably because it doesn't identify the 'teams.ID' in the subquery.
I managed to solve it using the Knex.raw function:
Knex.knex('teams')
.select('*', Knex.knex.raw('(SELECT COUNT(*) FROM team_users WHERE TeamID = teams.ID) AS UserCount'), Knex.knex.raw('(SELECT COUNT(*) FROM team_access WHERE TeamID = teams.ID) AS AppCount'))
.where("OwnerUserID", ownerId)
.asCallback(dataSetCallback);
but I am curious to know how to achieve this with the subqueries objects.
You are trying to pass teams.ID string as a value. To be able to do .where('columnName', 'otherColumnName') one has to use knex.ref to pass otherColumnName as an identifier.
var teamsIdColumnIdentifier = knex.ref('teams.ID'); // <-- [1]
var subquery1 = Knex.knex('team_users').count('*')
.where('TeamID', teamsIdColumnIdentifier).as('UserCount');
var subquery2 = Knex.knex('team_access').count('*')
.where('TeamID', teamsIdColumnIdentifier).as('AppCount');
Knex.knex.select('*', subquery1, subquery2).from('teams')
.where("OwnerUserID", ownerId).asCallback(dataSetCallback);
[1] Before knex.ref was added to Knex in May 2018, you had to use knex.raw, like this;
var teamsIdColumnIdentifier = knex.raw('??', ['teams.ID']);
I'm using Google Apps Script to update a MySQL table from Google Cloud SQL and I don't want to insert duplicate values, for example:
If I have the following table with a record
+----+--------+-----------+-------+
| id | name | address | phone |
+----+--------+-----------+-------+
| 1 | John | Somewhere | 022 |
+----+--------+-----------+-------+
| 2 | Snow | North | 023 |
+----+--------+-----------+-------+
Then I should not be able to execute a query that inserts a new record where
name=John,
address=Somewhere,
phone=022
or
name=Snow,
address=North,
phone=023
This is my current code that inserts new records to the database:
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(name, address, phone) values (?, ?, ?)');
stmt.setString(1, "John");
stmt.setString(2, "Snow");
stmt.setString(3, 022);
stmt.execute();
I have a date field (called: lastUpdate) on a firebase db.
How could I update that field using ng-grid on change from another field (say a separte field called: notes)?
Im using the following code to update my records on edit:
var cellEditableTemplate = "<input ng-class=\"'colt' + col.index\"
ng-input=\"COL_FIELD\" ng-model=\"COL_FIELD\"
ng-change=\"updateEntity(col,row)\"/>"
$scope.updateEntity = function (col, row) {
$scope.dblogs.$save(row.entity.$id);
};
Posted Below is my sample db being used:
uniqueIDajsdljfasdjfajsdf;jasdj
|
|
--->ticket
| |
| -->completed: true
| |
| -->dateUpdated: "(last activity date/time)"
| |
| -->notes: "need to update logger code today!"
|
---->username: "vr"