forked from HackYourFuture/databases
-
Notifications
You must be signed in to change notification settings - Fork 6
Vlad-week4-DB #29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vlnach
wants to merge
1
commit into
HackYourAssignment:main
Choose a base branch
from
vlnach:db-week4
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Vlad-week4-DB #29
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| require("dotenv").config(); | ||
| const { MongoClient, ServerApiVersion } = require("mongodb"); | ||
|
|
||
| const DB = "databaseWeek4"; | ||
| const COLL = "populations"; | ||
|
|
||
| async function totalPopulationPerYear(client, country) { | ||
| const col = client.db(DB).collection(COLL); | ||
| const pipeline = [ | ||
| { $match: { Country: country } }, | ||
| { | ||
| $addFields: { | ||
| Year: { $toInt: "$Year" }, | ||
| M: { $toLong: "$M" }, | ||
| F: { $toLong: "$F" }, | ||
| }, | ||
| }, | ||
| { | ||
| $group: { | ||
| _id: "$Year", | ||
| countPopulation: { $sum: { $add: ["$M", "$F"] } }, | ||
| }, | ||
| }, | ||
| { $sort: { _id: 1 } }, | ||
| ]; | ||
| return col.aggregate(pipeline).toArray(); | ||
| } | ||
|
|
||
| async function continentsForYearAge(client, year, age) { | ||
| const col = client.db(DB).collection(COLL); | ||
| const continents = [ | ||
| "AFRICA", | ||
| "ASIA", | ||
| "EUROPE", | ||
| "LATIN AMERICA AND THE CARIBBEAN", | ||
| "NORTHERN AMERICA", | ||
| "OCEANIA", | ||
| ]; | ||
| const pipeline = [ | ||
| { | ||
| $match: { | ||
| Country: { $in: continents }, | ||
| Year: { $in: [year, String(year)] }, | ||
| Age: age, | ||
| }, | ||
| }, | ||
| { | ||
| $addFields: { | ||
| Year: { $toInt: "$Year" }, | ||
| M: { $toLong: "$M" }, | ||
| F: { $toLong: "$F" }, | ||
| TotalPopulation: { $add: [{ $toLong: "$M" }, { $toLong: "$F" }] }, | ||
| }, | ||
| }, | ||
| // { $sort: { Country: 1 } } // optional | ||
| ]; | ||
| return col.aggregate(pipeline).toArray(); | ||
| } | ||
|
|
||
| async function main() { | ||
| const client = new MongoClient(process.env.MONGODB_URL, { | ||
| serverApi: ServerApiVersion.v1, | ||
| }); | ||
| await client.connect(); | ||
| try { | ||
| const nl = await totalPopulationPerYear(client, "Netherlands"); | ||
| console.log(nl); | ||
|
|
||
| const y2020 = await continentsForYearAge(client, 2020, "100+"); | ||
| console.log(y2020); | ||
| } finally { | ||
| await client.close(); | ||
| } | ||
| } | ||
|
|
||
| main().catch(console.error); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| // Week4/homework/ex2-transactions/index.js | ||
| import "dotenv/config"; | ||
| import { MongoClient } from "mongodb"; | ||
| import { setup } from "./setup.js"; | ||
| import { transfer } from "./transfer.js"; | ||
|
|
||
| const DB = "databaseWeek4"; | ||
| const COLL = "accounts"; | ||
|
|
||
| async function showAccounts(label) { | ||
| const client = new MongoClient(process.env.MONGODB_URL); | ||
| await client.connect(); | ||
| try { | ||
| const docs = await client | ||
| .db(DB) | ||
| .collection(COLL) | ||
| .find({}, { projection: { _id: 0 } }) | ||
| .sort({ account_number: 1 }) | ||
| .toArray(); | ||
| console.log(`\n=== ${label} ===`); | ||
| console.table( | ||
| docs.map((d) => ({ | ||
| account_number: d.account_number, | ||
| balance: d.balance, | ||
| last_change: d.account_changes?.[d.account_changes.length - 1], | ||
| })) | ||
| ); | ||
| } finally { | ||
| await client.close(); | ||
| } | ||
| } | ||
|
|
||
| async function main() { | ||
| await setup(); | ||
|
|
||
| await showAccounts("Before transfer"); | ||
|
|
||
| await transfer({ | ||
| from: 101, | ||
| to: 102, | ||
| amount: 1000, | ||
| remark: "lesson W4 transfer", | ||
| }); | ||
|
|
||
| await showAccounts("After transfer"); | ||
| } | ||
|
|
||
| main().catch(console.error); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| // Week4/homework/ex2-transactions/setup.js | ||
| import "dotenv/config"; | ||
| import { MongoClient } from "mongodb"; | ||
|
|
||
| const DB = "databaseWeek4"; | ||
| const COLL = "accounts"; | ||
|
|
||
| export async function setup() { | ||
| const client = new MongoClient(process.env.MONGODB_URL); | ||
| await client.connect(); | ||
| try { | ||
| const db = client.db(DB); | ||
| const col = db.collection(COLL); | ||
|
|
||
| await col.drop().catch(() => {}); | ||
| await db.createCollection(COLL); | ||
|
|
||
| await col.createIndex({ account_number: 1 }, { unique: true }); | ||
|
|
||
| const now = new Date(); | ||
| await col.insertMany([ | ||
| { | ||
| account_number: 101, | ||
| balance: 5000, | ||
| account_changes: [ | ||
| { | ||
| change_number: 1, | ||
| amount: 5000, | ||
| changed_date: now, | ||
| remark: "initial deposit", | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| account_number: 102, | ||
| balance: 1000, | ||
| account_changes: [ | ||
| { | ||
| change_number: 1, | ||
| amount: 1000, | ||
| changed_date: now, | ||
| remark: "initial deposit", | ||
| }, | ||
| ], | ||
| }, | ||
| ]); | ||
|
|
||
| console.log("setup: accounts seeded"); | ||
| } finally { | ||
| await client.close(); | ||
| } | ||
| } | ||
|
|
||
| if (import.meta.url === `file://${process.argv[1]}`) { | ||
| setup().catch(console.error); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| // Week4/homework/ex2-transactions/transfer.js | ||
| import { MongoClient, ServerApiVersion } from "mongodb"; | ||
| import "dotenv/config"; | ||
|
|
||
| const DB = "databaseWeek4"; | ||
| const COLL = "accounts"; | ||
|
|
||
| export async function transfer({ from, to, amount, remark }) { | ||
| if (!Number.isFinite(amount) || amount <= 0) { | ||
| throw new Error("Amount must be a positive number"); | ||
| } | ||
| if (from === to) { | ||
| throw new Error("From and To accounts must be different"); | ||
| } | ||
|
|
||
| const client = new MongoClient(process.env.MONGODB_URL, { | ||
| serverApi: ServerApiVersion.v1, | ||
| }); | ||
| await client.connect(); | ||
|
|
||
| const session = client.startSession(); | ||
| try { | ||
| const col = client.db(DB).collection(COLL); | ||
|
|
||
| const [a, b] = from < to ? [from, to] : [to, from]; | ||
|
|
||
| const result = await session.withTransaction( | ||
| async () => { | ||
| const [accA, accB] = await Promise.all([ | ||
| col.findOne({ account_number: a }, { session }), | ||
| col.findOne({ account_number: b }, { session }), | ||
| ]); | ||
| if (!accA || !accB) throw new Error("Account not found"); | ||
|
|
||
| const accFrom = accA.account_number === from ? accA : accB; | ||
| const accTo = accA.account_number === to ? accA : accB; | ||
|
|
||
| if (accFrom.balance < amount) { | ||
| throw new Error("Insufficient funds"); | ||
| } | ||
|
|
||
| const nextChangeFrom = | ||
| (accFrom.account_changes?.[accFrom.account_changes.length - 1] | ||
| ?.change_number ?? 0) + 1; | ||
| const nextChangeTo = | ||
| (accTo.account_changes?.[accTo.account_changes.length - 1] | ||
| ?.change_number ?? 0) + 1; | ||
|
|
||
| const now = new Date(); | ||
|
|
||
| const updFrom = await col.updateOne( | ||
| { _id: accFrom._id }, | ||
| { | ||
| $inc: { balance: -amount }, | ||
| $push: { | ||
| account_changes: { | ||
| change_number: nextChangeFrom, | ||
| amount: -amount, | ||
| changed_date: now, | ||
| remark, | ||
| }, | ||
| }, | ||
| }, | ||
| { session } | ||
| ); | ||
| if (updFrom.modifiedCount !== 1) { | ||
| throw new Error("Debit update failed"); | ||
| } | ||
|
|
||
| const updTo = await col.updateOne( | ||
| { _id: accTo._id }, | ||
| { | ||
| $inc: { balance: amount }, | ||
| $push: { | ||
| account_changes: { | ||
| change_number: nextChangeTo, | ||
| amount, | ||
| changed_date: now, | ||
| remark, | ||
| }, | ||
| }, | ||
| }, | ||
| { session } | ||
| ); | ||
| if (updTo.modifiedCount !== 1) { | ||
| throw new Error("Credit update failed"); | ||
| } | ||
| }, | ||
| { | ||
| readConcern: { level: "snapshot" }, | ||
| writeConcern: { w: "majority" }, | ||
| readPreference: "primary", | ||
| } | ||
| ); | ||
|
|
||
| if (result) { | ||
| console.log( | ||
| `transfer: success (from ${from} to ${to}, amount ${amount})` | ||
| ); | ||
| } else { | ||
| throw new Error("Transaction aborted by driver"); | ||
| } | ||
| } finally { | ||
| await session.endSession(); | ||
| await client.close(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: use better names for
aandb. It is hard to understand what they are for in the first sight.