Rails 5.1 store cryptocurrency values in postgresql database - ruby-on-rails-5.1

i want to make a rails app to keep track of my cryptocurrency coins.
How would you save the values in the database?
Which datatype field would you choose?
I thought about using the rails-money gem, but only BTC (Bitcoin) is set as a currency.
Thanks for you help
Benny

What does your schema look like? I would have something like a Balances and CoinTypes table.
In the balance table you would track the crypto amounts as integers (like one would do for whole cents in USD meaning Satoshi's for BTC). You would need to be able to hold huge numbers in this column. I would do something like t.integer :coin_amount :int5, :limit => 5
Whereas, in the coin type table under each coin you can track the amount of decimal places you need to divide the crypto_amount column by.
Balances
| ID | COIN_AMOUNT |TYPE | DESCRIPTION |
| ------------- |---------------|------|-------------|
| 1 | 2300000000000 | 1 | "Ledger" |
| 2 | 100000000 | 2 | "Coinbase" |
| 3 | 100000000 | 2 | "Gemini" |
CoinTypes
| ID | NAME |DECIMALS |
| ------------- |---------------|----------|
| 1 | "Ethereum" | 18 |
| 2 | "Bitcoin" | 8 |
Now you know you hold 1 BTC on Gemini and Coinbase respectively. You can also calculate the amount of ethereum you hold to be .0000023. I wouldn't store the dollar amounts in the database but rather calculate them using the api of whatever service you are holding your coins on.
A red flag to me though is that you are tracking balances on what I assume are external services. Remember if you don't manage the keys, they aren't your coins.

Related

What is this data referencing anti-pattern called?

I have a question related to a kind of duplication I see in databases from time to time. To ask this question, I need to set the stage a bit:
Let's say I have a database of TV shows. Its primary table Content stores information at various levels of granularity (Show -> Season -> Episode), using a parent column to denote hierarchy:
+----+---------------------------+-------------+----------+
| ID | ContentName | ContentType | ParentId |
+----+---------------------------+-------------+----------+
| 1 | Friends | Show | [null] |
| 2 | Season 1 | Season | 1 |
| 3 | The Pilot | Episode | 2 |
| 4 | The One with the Sonogram | Episode | 2 |
+----+---------------------------+-------------+----------+
Maybe this isn't ideal, but let's say it's good enough to work with and we're not looking to change it.
Now let's say we need to build a table that defines air dates. We can set these at any level, and they must apply down the hierarchy (e.g., if set at the Season level, it applies to all episodes within that season; if set at the Show level, it applies to all seasons and episodes).
So the original air dates might look like this:
+-------+-----------+------------+
| airId | ContentId | AirDate |
+-------+-----------+------------+
| 71 | 3 | 1994-09-22 |
| 72 | 4 | 1994-09-29 |
+-------+-----------+------------+
Whereas the air date for a streaming service might look like:
+-------+-----------+------------+
| airId | ContentId | AirDate |
+-------+-----------+------------+
| 91 | 1 | 2015-01-01 |
+-------+-----------+------------+
Cool. Everything's fine so far; we're adhering to 4NF (I think!) and we can proceed to our business logic.
Now we get to my question. If we implement our business logic in such a way that disregards the referential hierarchy, and instead duplicates the air dates down the hierarchy, what is this anti-pattern called? e.g., Let's say I set an air date at the Show level like above, but the business logic finds all child elements and creates an entry for each one, resulting in:
+-------+-----------+------------+
| airId | ContentId | AirDate |
+-------+-----------+------------+
| 91 | 1 | 2015-01-01 |
| 92 | 2 | 2015-01-01 |
| 93 | 3 | 2015-01-01 |
| 94 | 4 | 2015-01-01 |
+-------+-----------+------------+
There are some pretty clear problems with this, but please note that my question is not how to fix this. Just, is there a specific term for it? I want to call it something like, "disregarding data relationship" or, "ignoring referential context". Maybe it's not strictly a database anti-pattern, since in my example there's an external actor inserting the excess rows.

is this a good practice for a database for products with multiple units,cost price & expiry dates

I a working on a database that is going to have a product with multiple expiration date, multiple cost prices and therefore there will multiple stock entries for the same product, I have made an initial database design for this and I wanted to ask you guys if this is a good practice or not. If not please advise me on how to do it the right way.
This is what I have thought about so far.
Creating 3 tables (1. Product_info - 2.Product_Stock - 3.units)
and below is the detailed structure:
Units Table
--------------------------
id Name
|------|
1 |Piece |
2 |Pack |
3 |Kilos |
Here I will list all the units that I will use as the base product unit.
Product Information Table
-----------------------------------------------------------------------------------------------------------------------
id Name AvgCostPrice AvgPrice AvgPackCostPrice AvgPackPrice totalQuantity BaseUnitID multiplier PackBarcode Barcode
|------|------------|--------|----------------|------------|-------------|----------|----------|------------|--------|
1 |Soda | | | | | 108 | 1 | 12 | 111111 | 111222 |
2 |Water | | | | | 50 | 1 | 6 | 222222 | 222111 |
in the above table the average cost price and selling price for the packs and piece will be calculated from the different stocks I have for the said product.
The multiplier column will be for how much pieces does a product pack hold.
The Total Quantity will hold the sum of different stock quantities I have in the (Product Stock Table) ,Also it will only sum the quantity for base unit of the product.
for example: if the base unit of soda is pack, then it will sum the (PackQTY) Column in (Product Stock Table). and if else it will sum (Quantity) in that table.
Product Stock Table
---------------------------------------------------------------------------------------------------------------------------
id ProdID UnitID CustomBarcode Quantity PackQTY CostPrice Price PackCostPrice PackPrice expDate Enabled
|------|-------|--------------|-------------|-------|----------|-------|--------------|---------|--------------|---------
1 |1 | 1 | | 84 | 7 | 2.0 | 2.4 | 24.0 | 29 | 20/may/2019 | 1
2 |1 | 1 | | 24 | 2 | 1.5 | 1.9 | 18.0 | 23 | 10/aug/2019 | 1
2 |2 | 3 | | 50 | 0 | 3.0 | 5.0 | 0.0 | 0 | 10/Feb/2019 | 1
1.The enabled column will work as a (Boolean) to determine whether to use this stock while selling.
for example: if I wanted to sell a soda Can and I have two Stocks for it. if stock number one is 0 then enable column will be false and therefore it will only subtract the quantity sold from stock number two and use its price and cost price in the (SalesDetails Table)
Custom Barcode Column will be used to separate stocks when having a discount on almost expired stock.
And I also thought of separating the different units for each product stock in (Stock Table)
So, when I want to sell 24 pieces of soda and 3 packs of soda it will choose the oldest stock depending on its (Enabled Column Value = True)and subtract that quantity from it and if it reaches zero then (Enabled column) Value will change to false.
after that it will go again and do the same but this time it will change the value of PackQtY from 7 to 4 and the Quantity Column Value will be calculated through this [ Product_Stock.Quantity= Product_Stock.Quantity - (QtySold * Prodcut_info.Multiplier Column Value) ] which will be 84-(3*12)= 48
And the sales details structure output will be like this:
Sale Details Table
----------------------------------------------------------
id ProdID UnitID Quantity CostPrice Price total CostTotal
|------|-------|-----------|-------------|-------|------|---------|
1 |1 | 1 | 24 | 2.0 | 2.4 | 57.6 | 48.0 |
2 |1 | 2 | 3 | 18.0 | 23.0 | 69.0 | 54.0 |
Product Stock Table (After Selling 24 pieces of Soda and 3 packs of Soda)
---------------------------------------------------------------------------------------------------------------------------
id ProdID UnitID CustomBarcode Quantity PackQTY CostPrice Price PackCostPrice PackPrice expDate Enabled
|------|-------|--------------|-------------|-------|----------|-------|--------------|---------|--------------|---------
1 |1 | 1 | | 48 | 4 | 2.0 | 2.4 | 24.0 | 29 | 20/may/2019 | 1
2 |1 | 1 | | 0 | 0 | 1.5 | 1.9 | 18.0 | 23 | 10/aug/2019 | 0
Sorry if I didn't explain it very well.
Thank you very much in advance.
Firstly, you need to be careful about how you use nouns.
For example: "Price" does not mean the same as "Cost" and "CostPrice" sounds like an oxymoron. I suggest that you restrict your yourself to using either Cost or Price.
Van Ng asks if you have done an Entity Relationship diagram. Well, at the stage that you seem to be at, it is probably unwise to start with an ER diagram because an ER diagram is helpful as a summary of a model that you have already defined - and you are not yet at that stage.
Averages: If you design your database schema correctly then you can calculate data such as averages. You don't need averages as base tables.
I recommend that you consider using the fact-based modeling method called "object-role modeling"(ORM) because you can start with "the facts" before thinking about drawing ER diagrams.
Example:
I used the NORMA ORM tool to create the following example:
First, I read your text, extracted facts and then used the facts to design an object-role model.
Then I used the NORMA tool to generate a "logical view" of the object-role model. (happens in milliseconds)
I did not add everything that you mention but I hope that this will be enough to help you to make progress.
The example contains two artefacts:
1: The logical model that was generated by the NORMA tool.
2: The facts from which the logical model was generated.
[

Using Data from One Table in Another Table in Access

Hallo StackOverflow Users
I am struggling with transferring values between Access database tables which I will use in a Delphi program to tally election votes and determine the winning candidates. I have a total of six tables. One is my overall table, tblCandidates which identifies each candidate and contains the amount of votes they received from each party, namely the Grade Heads, the Teachers and the Learners. When it comes to the Learners we have four participating grades, namely the grade 8’s, 9’s, 10’s and 11’s, and each grade again has multiple participating classes, namely class A, B, C, etc.
Now, I have set up tables for each grade that contains all the classes in that grade. I named these tables tblGrX with X being the grade represented by 8 through 11. Each one of these tables has two extra fields, namely a field to identify a candidate and a field that will add up all the votes that candidate received from each of the classes in that grade. Lastly I have another table, tblGrTotals with fields Total_GrX (once again with X being the grade), that will contain all the total votes a candidate received from each grade, adding them up in another field for my tblCandidates table to use in its Total_Learners field.
So in short, I want, for example, tblGrTotals to use the value in the field Total of tblGr8 in its Total_Gr8 field, and then tblCandidates to use the value in field Total of tblGrTotals in its Total_Learners field. Is there any way to keep these values updated between tables like cells are updated in Excel the moment a change is made?
Thank you in advance!
You need to rethink your table design. I guess your background is Excel, and your tables are laid out like you would do in Excel sheets, but a relational database works differently.
Think about the objects you are modelling.
Candidates - that's easy. ID, Name, perhaps additional info that belongs to each candidate. But nothing about votes here.
"Groups that are voting" or Parties. Not so trivial, due to the different types of parties. Still I would put them in one table, with Grade and Class only set for Learners, NULL for Heads and Teachers.
e.g.
+----------+------------+-------+-------+
| Party_ID | Party_Type | Grade | Class |
+----------+------------+-------+-------+
| 1 | Head | | |
| 2 | Teacher | | |
| 3 | Learner | 8 | A |
| 4 | Learner | 8 | B |
| 5 | Learner | 8 | C |
| 6 | Learner | 9 | A |
| 7 | Learner | 9 | B |
| 8 | Learner | 10 | A |
+----------+------------+-------+-------+
Votes: they are a Junction Table between Candidates and Parties.
e.g.
+----------+--------------+-----------+
| Party_ID | Candidate_ID | Num_Votes |
+----------+--------------+-----------+
| 1 | 1 | 5 |
| 1 | 2 | 17 |
| 3 | 1 | 2 |
| 3 | 2 | 6 |
| 3 | 3 | 10 |
+----------+--------------+-----------+
Now: if you want to know the votes of Class 8A:
SELECT Candidate_ID, SUM(Num_Votes)
FROM Parties p INNER JOIN Votes v
ON p.Party_ID = v.Party_ID
WHERE p.Party_Type = 'Learner'
AND p.Grade = 8
AND p.Class = 'A'
GROUP BY Candidate_ID
Or of all Grade 8? Simply omit the p.Class criteria.
For the votes per candidate you join Candidates with Votes.
Edit:
for the votes counting differently, this is an attribute of Party_Type.
We don't have a table for them yet, so create one:
+------------+---------------+
| Party_Type | Multiplicator |
+------------+---------------+
| Head | 4 |
| Teacher | 3 |
| Learner | 1 |
+------------+---------------+
and to count all votes:
SELECT c.Candidate_ID, c.Candidate_Name, SUM(v.Num_Votes * t.Multiplicator) AS SumVotes
FROM Parties p
INNER JOIN Votes v ON p.Party_ID = v.Party_ID
INNER JOIN Party_Types t ON p.Party_Type = t.Party_Type
INNER JOIN Candidates c ON v.Candidate_ID = c.Candidate_ID
GROUP BY c.Candidate_ID, c.Candidate_Name
With a design like this, you don't need to keep updating data from one table into another - you calculate it when and how you need it, and it's always current.
The magic of databases. :)

Django QuerySet - Multiple Order By when there is a single field per record

I am accessing an API where the number of fields can change at any time, but I must store and display the data as a table. Therefore, each record from the API is stored as a single record per field. My problem is that I am having trouble working out how I would order by multiple columns at a time. Putting all of the data into a 2D array (list of lists) before sorting is not a viable option as the number of records could be too large to feasibly hold in memory.
I've put together a simple example to explain. If anyone has an idea on how to overcome the problem, or how I could redesign my approach, I'd be very grateful.
| record_id | field | data |
| 1 | x | 2 |
| 1 | y | 1 |
| 1 | z | 3 |
| 2 | x | 30 |
| 2 | y | 42 |
| 2 | z | 7 |
| 3 | x | 53 |
| 3 | y | 2 |
| 3 | z | 7 |
If ordering by fields 'z' then 'x' (both ascending), the record order would be 1,2,3
If ordering by fields 'z' then 'y' (both ascending), the record order would be 1,3,2
I am using models in django to store and I am using QuerySets to retrieve the data. I don't have any control over the API or database from which I am originally accessing the data.
After a fair amount of research I realised I was going about this all wrong - I am now using an hstore field in postgres and django-hstore to utilise it, for a schema-less approach. I now have a single row per original record and I can order_by after casting the required field in an 'extra' method.

Ingredients for drink new table or string in column?

I am thinking about my application and I want to store data about drinks. Now I am thinking what is best that if I save ingredients just as nvarchar column in table with drink or if I create new table with ingredients and create relationship one to many? I want database to be just read-only and I want to have option filter by ingredients. So what´s best way for windows phone (for performance)? And if the new table would be the better choice, I should use EntitySet, EntityRef, am I right? And I would have for every ingredient new row in table? Let´s say I have 100drinks, in average that every drink has 4ingredients so I have in first table 100rows and in second cca 400rows? Thanks for help
Actually, both solutions proposed are wrong. A drink can have many ingredients and an ingredient can be used in many drinks. Hence, we have a many-to-many relationship here. The proper way to model this is the following (I'm adding data for it to be more understandable):
Ingredients (PK: Id)
+----+--------------------+
| Id | Name |
+----+--------------------+
| 1 | Water |
| 2 | Sugar |
| 3 | Coffe |
| 4 | Virgin Islands Tea |
| 5 | Ice |
+----+--------------------+
Drinks (PK: Id)
+----+-------------+
| Id | Name |
+----+-------------+
| 1 | Black Coffe |
| 2 | Tea |
| 3 | Ice Tea |
+----+-------------+
Drinks_Ingredients (PK: Drink_Id, Ingredient_Id)
+----------+---------------+------------+
| Drink_Id | Ingredient_Id | Proportion |
+----------+---------------+------------+
| 1 | 1 | 70 |
| 1 | 2 | 10 |
| 1 | 3 | 20 |
| 2 | 1 | 90 |
| 2 | 4 | 10 |
| 3 | 1 | 80 |
| 3 | 4 | 10 |
| 3 | 5 | 10 |
+----------+---------------+------------+
I'm adding this Proportion column to show you how to add data that is dependant on the pair of drink-ingredient. Now, if you're worried about the size of the tables it'll be quite small as the only tables that will have the more complex data types (varchars) will be the ingredients and drinks tables, which will have the minimum amount of records possible: one per each drink and one per each ingredient.
If you still have doubts keep looking at the example, you'll get it :)
I would do a table for ingredients with a description and an id, and store the ids in the drink table cause it's the elegant way to do it. For 100 drinks, you won't see a difference for the performance.

Resources