206 points · by swyx · 4y ago · 247 comments
It was super handy to simply query that table to debug things, since by merely looking for a user, you’d discover everything. If Mongo was more mature and scalable back then (2012ish), I wonder if we would have used it.
The issue with this is schema management and rules gets pushed to the application layer. You also need to deal with very massive tables (in terms of # of rows) for the relationships table which leads to potential performance issues.
1.you can't have strongly typed schemas specific to a 'thing' subtype; to store it all together, you end up sticking all the interesting bits in a JSON field
2. any queries of interest require a lot of self joins and performance craters
Please, please, never implement a "graph database" or "party model" or "entity schema" in a normal RDBMS, except perhaps at miniscule scale; the flexibility is absolutely not worth it.
As for performance issues, using a dedicated Quad store helps there, rather than one built on top of an RDBMS (OpenLink Virtuoso excluded, because somehow they manage to make Quads on top of a distributed SQL engine blazing fast).
It's been about 6 years since I've been in that world, so things might have changed wrt performance.
I'm not really sure I understand why not having that constraint is helpful - what sort of 'changes' are significantly cheaper? Schema changes on the thing ('dimension') tables? Or do you mean cheaper in the 'reasoning about it' sense, you can delete a thing without having to worry about whether it should be nullified, deleted, or what in the relationship table? (And sure something starts to 404 or whatever, but in this application that's fine.)
Pretty much this. You could just delete all the relationships, or just some of them. For example, a user could be related to many things (appointments, multiple vendors, customers, etc). Thus a customer can just delete the relationship between them and a user, but the user still keeps their other relationships with the customer (such as appointments, allowing them to see their appointment history, even though the customer no longer has access to the user's information).
Sounds like objects and associations in the Tao model:
https://engineering.fb.com/2013/06/25/core-data/tao-the-powe...
How big was the relationships table? How was performance?
We didn't know it at the time, but you can get the date of creation from them. Which means... If you sort by ObjectID, you're actually sorting by creation time. You can create a generic ObjectID using JavaScript and filter by time ranges. I still have a codepen proof of concept I did for doing ranges.
Anyway, the other thing is, and I'm not sure how many people use it this way: you can copy an ObjectID verbatim into other documents, like a foreign key, so you can reference between collections. If you do this, you'll save yourself a lot of headaches. Just because you can shove anything and everything into MongoDB documents, doesn't mean you absolutely should.
* Most relations are properly modeled as N:N anyways.
* Corollary: no "aargh, need to upgrade this relation to N:N" regrets.
* Corollary: no 1000 relationship tables to name & chase around the DB metadata.
* Low friction to add relations on-the-fly when developing code.
* Low friction to query all relations associated with an object.
* Low friction to update a relation, but keep the ex around.
Neat approach IMHO.
I'm not sure that's true. Containment is a very common type of relationship.
>Corollary: no 1000 relationship tables to name & chase around the DB metadata.
That depends on whether relationships have associated attributes. If and when they do, you have to turn them into object types and create a table for them. And it's exactly the N:M relationships that tend to have associated information.
That's the conceptual problem with this approach in my view. Quite often, there isn't really a conceptual difference between relationship types and object/thing types. So you end up with a model that allows you to treat some relationships as data but not others.
>Neat approach IMHO.
It's a valid compromise I guess, depending heavily on the specifics of your schema. Ultimately, database optimisation is a very dirty business if you can't find a way to completely separate logical from physical aspects, which turns out to be a very hard problem to solve.
* aaargh we have trillion row tables that contain everything, how do we scale this (you don't)
* aaargh our tables indices don't fit into memory, what do we do (you cry)
* no at a glance metrics like table sizes to have an idea of which relations are growing
* oh no we have to have complex app code to re-implement for relationships everything a database gave for free
Reddit used a similar system in Posgresql and hit all of these issues before moving to Cassandra. Even then they still had to deal with constraints of the original model.
Edit: Didn't even read the article being about Reddit, it pretty much confirms what I said. It took them something like 2 years iirc to migrate to Cassandra and the site was wholely unuseable during that time. There is no doubt in my mind if another Reddit style site existed during that time it would have eaten their lunch same as Reddit ate Diggs lunch (for non technical reasons).
Furthermore, back then iirc they only really had something like 4 tables/relations: comment, post, user, vote. The 'faster development time' adding new relations was completely moot, they spent more time developing and dealing with a complex db query wrapper and performance issues (caching in memcache all over the place) than actual features.
The (app+query) code and performance for their nested comments was absolutely hilarious. Something a well designed table would have given then for free in one recursive CTE.
It wasn't until they moved to Cassandra that they were able to let the db do that job and work on adding the shit ton of features that exist today.
No, database constraints declaratively specify invariants that have to be valid for the entirety of your data, no matter when it was entered.
Checks and constraints in code only affect data that is currently being modified while that version of the code is live. Unless you run regular "data cleanup" routines on all your data, your code will not be able to fix existing data or even tell you that it needs to be fixed. If you deployed a bug to production that caused data corruption, you deploying a fix for it will not undo the effects of the bug on already created data.
Now, a new database constraint will also not fix previously invalid data, but it will alert you to the problem and allow you to fix the data, after which it will then be able to confirm to you that the data is in correct shape and will be continue to be so in the future, even if you accidentally deploy a bug wherein the code forgets to set a reference properly.
I'm fine with people claiming that, for their specific use case or situation, database constraints are not worth it (e.g. for scalability reasons), but it seems disingenuous to me to claim that code can provide "just as much safety".
This statement is absolutely false. Some application code that random developers write will never be a match for constraints in a mature, well tested database.
Then how did the relationship table refer to things in the thing tables?
> we had tables for each thing
I take that to mean "a separate table for each class of thing." So the single "relationship" table had to somehow refer not just to rows in tables but to the tables themselves. AFAIK that is not possible to do directly in SQL. You would have to query the relationship table, extract a table name from the result, and then make a separate query to get the relevant row from that table. And you would have to make that separate query for every relationship. That would be horribly inefficient.
Generally, the relationship table will look like this:
- relation1_id
- relation1_type
- relation2_id
- relation2_type
Where *_id is the database ID and *_type is some kind of string constant representing another table. Generally you put an index on "relation#_id, relation#_type", but that's obviously use case dependentBut here's the neat part. That's often only for safety.
If I want to find all users and their orders, I can join the user table to the relationship table, then join that to the order table. Something like:
SELECT <COLUMNS GO HERE> FROM USER INNER JOIN RELATIONSHIP ON USER.Id IN (RELATIONSHIP.LeftId, RELATIONSHIP.RightId) INNER JOIN ORDER ON ORDER.Id IN (RELATIONSHIP.LeftId, RELATIONSHIP.RightId)
So you're getting the Users. The filtering the ones that have relationships, then filtering that to the ones that also have orders.
If you've ever managed an N:N relationship table, it's like that, but more generic.
I am assisting a professor with his intro to databases class this semester and that was the first thing taught there
https://en.wikipedia.org/wiki/Entity%E2%80%93relationship_mo...
In 2022, there are so many more mature, reliable, battle-tested NoSQL options that could have solved their problem more elegantly.
But even today, if I were to build Reddit as a startup, I'd start with a Postgres database and go as far as I can. Postgres allows me to use relations when I want to enforce data integrity and JSONB when I just want a key/value store.
This is accepted wisdom on HN but I don't see it:
- True HA is very difficult. Even just automatic failover takes a lot of manual sysadmin effort
- You can't autoscale, and while scaling is a nice problem to have, having to not just fundamentally rearchitect all your code when you need to shard, but also probably migrate all your data, is probably the worst version of it.
- Even if you're not using transactions, you still pay the price for them. For example your writes won't commit until all your secondary indices have been updated.
- If you're actually using JSONB then driver/mapper/etc. support is very limited. E.g. it's still quite fiddly to have an object where one field is a set of strings / enum values and have a standard ORM store that in a column rather than creating a join table.
>True HA is very difficult. Even just automatic failover takes a lot of manual sysadmin effort
Nearly all Postgres cloud providers such as RDS, CloudSQL, Upcloud, provide multi-region nodes and automatic failover.
Also, true HA databases are very expensive and have their own drawbacks. Not really designed for a Reddit-style startup.
>You can't autoscale, and while scaling is a nice problem to have, having to not just fundamentally rearchitect all your code when you need to shard, but also probably migrate all your data, is probably the worst version of it.
Hence why I said "as far as I can". I can keep upgrading the instance, creating material views, caching responses, etc.
Lastly, the most important reason is because I know Postgres and I can get started today. I don't want to learn a highly scalable, new type of database that I might need 5 years down the road.
From memory you have to specify a maintenance window and failover is not instant. And relying on your cloud provider comes with its own drawbacks.
> Also, true HA databases are very expensive and have their own drawbacks. Not really designed for a Reddit-style startup.
Plenty of free HA datastores out there, and if we're assuming it'll be managed by the cloud provider anyway then that's a wash.
> Lastly, the most important reason is because I know Postgres and I can get started today. I don't want to learn a highly scalable, new type of database that I might need 5 years down the road.
That's a good argument for using what you know; by the same token I'd use Cassandra. Postgres is a very complex system with lots of legacy and various edge cases.
It turns out that SQL is crucial to non-app-developers such as business analysts, data scientists. Trying to setup an ETL to pull data from your MongoDB datastore to a Postgres DB so the analysts could generate reports is such a waste of time and resources. Or worse, the analysts have to request devs to write Javascript code to query the data they need. For this reason alone, I will always start with a DB that supports SQL out of the box.
The entire database world has been working ever since trying to get back those RDBMS features into their horizontally scalable solutions, it's just taken a while because the problems are exponentially harder in a network. It's not like people are using eventual consistency and a loss of referential integrity because they prefer it.
I agree that this should have been the reason for choosing something like MongoDB over MySQL/Postgres.
In reality, I saw a lot about the companies switching/starting with because so their devs didn't have to learn SQL and they can just stay in Javascript/whatever language they were using.
Hbase was a pretty solid NoSQL option by 2010, no?
Because it requires no setup and has been used to scale typcial Web2 applications to millions in revenue on a single cheap VM.
Another option worth taking a look at is to use no DB at all. Just writing to files is often the faster way to get going. The filesystem offers so much functionality out of the box. And the ecosystem of tools is marvelous. As far as I know, HN uses no DB and just writes all data to plain text files.
It would actually be pretty interesting to have a look at how HN stores the data:
What am I missing?
- Postgres backups are not trivial. They aren't hard, but well SQLite is just that one file
- Postgres isn't really built for many-cardinal-DB setups (talking on order of 100s of DBs). What does this mean in practice? If you are setting up a multi-tenant system, you're going to quickly realize that you're paying a decent cost because your data is laid out by insertion order. Combine this with MVCC meaning that no amount of indices will give you a nice COUNT, and suddenly your 1% largest tenants will cause perf issues across the board.
SQLite, meanwhile, one file per customer is not a crazy idea. You'll have to do tricks to "map/reduce" for cross-tenant stuff, of course. But your sharding story is much nicer.
- PSQL upgrades are non-trivial if you don't want downtime. There's logical upgrades, but you gotta be real fucking confident (did you remember to copy over your counters? No? Enjoy your downtime on switchover).
That being said, I think a lot of people see SQLite as this magical thing because of people like fly posting about it, without really grokking that the SQLite stuff that gets posted is either "you actually only have one writer" or "you will report successful writes that won't successfully commit later on". The fundamentals of databases don't stop existing with a bunch of SQLite middleware!
But SQLite at least matches the conceptual model of "I run a program on a file", which is much easier to grok than the client-server based stuff in general. But PSQL has way more straightforward conflict management in general
Grabbing a copy of the file won't necessarily work: you need at atomic snapshot. You can create those using the backup API or by using VACUUM INTO, but in both cases you'll need enough spare disk space to create a fresh copy of your database.
I'm having great results from Litestream streaming to S3, so that's definitely a good option here.
How do you get enough time to back up that file when it's in use? Lock the file until you've copied it? zfs?
I immediately started to have problems as expected, and later migrated to an Access DB. It didn't support concurrent writes, but it was an improvement beyond comprehension. Even "orders of magnitude" doesn't cut it because you get many more luxuries than performance like data-type consistency, ACID compliance, relational integrity, SQL and whatnot.
You haven't lived until you've built an in-memory database with background threads persisting to JSON files. Oh, the nightmares.
Different requirements, expertise, and priorities. I don't like generic advice too much because there are so many different situations and priorities, but I've used files, SQLite and PostgreSQL according to the priorities:
- One time we needed to store some internal data from an application to compare certain things between batch launches. Yes, we could have translated form the application code to a database, but it was far easier to just dump the structure to a file in JSON, with the file uniquely named for each batch type. We didn't really need transactions, or ACID, or anything like that, and it worked well enough and, importantly, fast enough.
- Another time we had a library that provided some primitives for management of an application, and needed a database to manage instance information. We went for SQLite there, as it was far easier to setup, debug and develop for. Also, far easier to deploy, because for SQLite it's just "create a file when installing this library", while for PostgreSQL it would be far more complicated.
- Another situation, we needed a database to store flow data at high speed, and which needed to be queried by several monitoring/dashboarding tools. There the choice was PostgreSQL, because anything else wouldn't scale.
In other words, it really depends on the situation. Saying "use PostgreSQL always" is not going to really solve anything, you need to know what to apply to each situation.
We're responding to this below. The requirement is a Web2 app with "millions in revenue".
>Because it requires no setup and has been used to scale typcial Web2 applications to millions in revenue on a single cheap VM.
This has only been practical within the last 6 years or so. Big servers were just too expensive. We started using cheap commodity low-resource PCs, which are cheaper to buy/scale/replace, but limits what your apps can do. Bare metal went down hard and there wasn't an API to quickly stand up a replacement. NAS/SAN was expensive. Network bandwidth was limited.
The cloud has made everything cheaper and easier and faster and bigger, changing what designs are feasible. You can spin up a new instance with a 6GB database in memory in a virtual machine with network-attached storage and a gigabit pipe for like $20/month. That's crazy.
What you're missing is complexity and second order effects.
Making decisions about databases early results in needing to make a lot of secondary decisions about all sorts of things far earlier than you would if you just left it all in sqlite on one VM.
It's not for everyone. People have varying levels of experience and needs. I'll almost always setup a MySQL db but I'd be lying if I said it never resulted in navel gazing and premature db/application design I didn't need.
Like what? What could be easier than going to AWS, click a few things to spin up a Postgres instance, click a few more things to scale automatically without downtime, create read replicas, have automatic backups, one-click restore?
I feel like it's the opposite. Trying to put SQLite on a VM via Kubernetes will likely have a lot of secondary decisions that will make "scaling to millions" far harder and more expensive.
how come?
At first i was writing in a large json file. Each time i did a change, I would write the file and close it.
It worked pretty well. I now use sqlite+dataset and the port was trivial.
I guess there are better ways to do it than open(), but using dataset is quite simple.
Maybe creating folders and duplicating data works, but it seems more complex than using sqlite and dataset.
Cloud SQL postgres on GCP with <50 connections is like ~$8/month and has automated daily backups.
The differences in SQL syntax between SQLite and Postgres, namely around date math (last_ping_at < NOW() - INTERVAL '10 minutes'), make SQLite a non-starter imho... you're going to end up having to rewrite a lot of sql queries.
Where "some" may include "none" ;)
only that hn is full, FULL of trolls who give the absolute worst advice possible. it's a sport maybe or it's entirely innocent and related to the Dunning Kruger effect but nothing brings it out more than database threads.
>Because it requires no setup and has been used to scale typcial Web2 applications to millions in revenue on a single cheap VM.
Plenty of setup. How would you secure your VM? SSL configuration? SSL expiration management? Security? How would you scale your VM to millions without downtime? Backups? Restoring backups?
All these problems are solved with managed database hosting.
The argument boils down to how the relative performance costs of databases have changed in the 30 years since MySQL/Postgres were designed - and the surprising observation that a read from a fast SSD is usually faster than a network call to memcached.
[1] https://fly.io/blog/all-in-on-sqlite-litestream/ [2] https://www.usenix.org/publications/loginonline/jurassic-clo...
Better, it runs in the same process.
You also aren’t getting that for $15/mo, either.
There are hundreds of posts that people are reading at every moment. I don't think it's that less.
Or take a quantitative approach. HN item IDs are sequential. Using the API:
$ curl 'https://hacker-news.firebaseio.com/v0/maxitem.json'
32409711
$ curl -s "https://hacker-news.firebaseio.com/v0/item/32409711.json" | jq .time
1660125598
$ curl -s "https://hacker-news.firebaseio.com/v0/item/$(( 32409711 - 14400 )).json" | jq .time
1660031940
so, 14400 items in ~26 hours, fewer than 10 items per minute on average. At the peak you'll see somewhat more than that.But if you spread your compute across many machines that access a single database it can get iffy. If you need the database accessible through network there are server extensions which use SQLite as storage format but you're dealing with a server and probably could use any other database without much difference in deployment&maintenance.
You could cobble something together with rsync, etc, but then you have added a bunch of complexity and built a custom and unproven system. Another option is to use one of the SQLLite extensions popping recently like Dqlite, but again, this approach is relatively unproven for basing your entire business on.
Or you could simply use an off the shelf DBMS like Postgres or even MySQL. They already solve all of these problems and are as battle-tested as can be.
Depends very much on the business. You can have downtime-free deploys on a single node, and as long as you've setup a system to automatically replace a faulty node with a new one (which typically takes < 10min) then a lot of businesses can live with that just fine. It's not like that cheap VM goes down every day, but just in case you can usually schedule a new instance every week or so to reduce the chance of that happening.
> How do you handle regional replication?
For backup purposes, you'd use litestream. Very easy to use with something like systemd or as a docker sidecar.
For performance purposes, if you do need that performance you'd obviously use something else. Depending on the type of service you have, though, you can get very far with a CDN in front of your server.
> Or you could simply use an off the shelf DBMS like Postgres or even MySQL.
If you need it, sure.
People get too caught up in assumptions without knowing the use case. There are a million use cases where a tool like sqlite would be bad, but also a million where its likely the easiest and best tool.
Wisdom is knowing the difference.
There's a whole page in the docs explaining why this might be a bad idea for a write-heavy site:
https://www.sqlite.org/howtocorrupt.html
Section 2 is especially interesting. SQLite locks on the whole database file - usually one per database - and that is a major bottleneck.
> Another option worth taking a look at is to use no DB at all.
We tried that in a project I'm currently in as a means of shipping an MVP as soon as possible.
Major headache in terms of performance down the road. We still serve some effectively static stuff as files, but they're cached in memory, otherwise they would slow the whole thing down by an order of magnitude.
I'm using it to create an embeddable out of the box passwordless auth system that has no external dependencies. Works great.
Admittedly I've not tried it under extreme load yet, but I'm happy to migrate it onwards if something I create goes massive.
(Edit: to be clear it is NoSQL, but you can query it using almost standard SQL which is what I do).
A simple schema helps when you just need to write stuff. You can make simple queries against a simple schema, directly.
For the juicier queries what you do is you derive new tables from the data using ETL or map/reduce. The complexity of the underlying schema doesn’t have to reflect the complexity of your more complicated queries. It only needs to be complex enough to let you store data in its base form and make simple queries. Everything else can be derived on top of that, behind the scenes.
Example: nodes are people and edges represent friendships, and then from this you could derive a new table of best_friend(id, bf_id, since).
1. There are no solutions, only tradeoffs.
Sure. You win in the OP example of easy to add things but you lose in the relational aspects.
You could say the same thing in reverse, using a RDBMS make it much easier to do join based lookups but then it's harder to update
2. At the end of the day, it doesn't matter b/c some other layer will do what your base layer can't
I've seen some really atrocious approaches to storing data in systems that were highly regarded by the end users. How did this happen? Someone went in and wrote an abstraction layer that combined everything needed into an easy to query/access interface. I've seen this happen so many times that whenever people start trying to future proof something I mention this point. You will get the design wrong and/or things will change. That means you either change the base layer or you modify/create an abstraction layer.
There are a lot of objectively wrong ways to do something. But among all the right ways, there are trade offs.
There is no right or wrong, only working and not-working.
The Perl community themselves eventually extended the motto to "There's more than one way to do it, but sometimes consistency is not a bad thing either"
Prof: "Why do we normalize?"
Class, in unison: "To make better relations."
Prof: "Why do we denormalize?"
Class, in unison: "Performance."
It took a lot of years of work before the simplicity of the lesson stuck with me. Normalization is good. Performance is good. You trade them off as needed. Reddit wants performance, so they have no strong relations. Your application may not need that, so don't prematurely optimize.
oh, and also, the entire point is that neither is "inherently better"... both have pros and cons
On the flip side, "normalization" doesn't have that same inherent good-ness. All things being equal (including performance) there isn't any inherent drive toward more normalization, maybe because a faster performing page will have clear impact to the user while a more normalized data structure would be completely transparent to the user?
Example: When you have the same data in two places, which is authoritative? If they disagree, which one is right?
And querying data reliably is much easier when you've got good relations that can be relied on to be accurate. SQL is almost a masterpiece (though imho it should have been FROM, WHERE, SELECT).
Premature optimization is the root of all evil
You may end up using them as arguments when they're just catchphrases that require context.
See people who used "goto considered harmful" as an absolute to never use goto (C).
Seriously true, though. What's usually missed is the first bit, about "small efficiencies", combined with the last bit, the "critical 3%". He's basically saying don't spend time in the mass of weeds until you know where the problems really are, but conversely take the time to optimise the smaller areas that are performance-critical.
Almost the opposite of the carte-blanche overly-minimal MVPs often thrown together by those of us who forget what the V stands for.
More _memory_ and row caching in RAM has allowed for a resurgence in denormalized schema.
FB's underlying schema is similarly just a few tables. But the entire dataset is memcached.
Interesting. Do you know what causes this steep decline in performance?
A larger sequential read is typically not that much slower regardless on what sort of drive you are using. I'd have expected that the random access pattern of a normalized table would lose out.
Reddit's database has only two tables - https://news.ycombinator.com/item?id=4468265 - Sept 2012 (79 comments)
A single Aurora RDS database (with read replicas), with a single table called “blobs”. The blobs table has three columns: id, type, and json.
It’s scaling really really well, to many many millions of rows, and high traffic volumes (many thousands of writes per second).
PostgreSQL supports setting values, appending to arrays, etc etc natively in an ACID compliant way.
Also supported in DynamoDB - it's a JSON-database after all.
> update deepely nested fields in the JSON natively as well
https://docs.aws.amazon.com/amazondynamodb/latest/developerg...
> PostgreSQL supports setting values, appending to arrays, etc etc natively in an ACID compliant way.
https://aws.amazon.com/blogs/aws/new-amazon-dynamodb-transac...
I'm not saying PostgreSQL is a bad choice by any means, or that DynamoDB is suitable for all projects. But good support for JSON is in no way a capability unique to PostgreSQL. At least ideally, a competently built document database should be at least as good if not better than an SQL database emulating a document database.
Or, at that point, just use a CSV and slurp the whole thing into memory.
1) There's an incident and we are trying to replicate the issue, but our database is just shapeless blobs and we can't track down the data that is pertinent to resolving the issue.
2) Product management wants to better understand our users and what they are doing so that they can design a new feature. But they can't figure out how to query our database or how to make sense of the unstructured data.
3) QA wants to be able to build tests and set up test data sets that match those tests, but rather than a sql script, they've got to roll all this json that doesn't have any constraints.
These are just some examples, but maybe you get the gist of why I don't quite understand how this model scales "outside" the database.
2) Very true. We're using other tools (like PostHog) for collecting and analysing user behaviour. At a bigger scale, we'd probably ship of event data to something like BigQuery for analysis.
3) We don't have QA, but for testing, objects are created in code just like any other object, and unit tests (aka most of the tests), don't need the database at all. :-)
Even today, it should be pretty straightforward to port the data over to a NoSQL db.
https://www.reddit.com/r/counting/comments/ww3vr/i_am_the_be...
Their data model was not designed for very deep comment chains.
The physical schema ought not be a transactional change, but it is in most products, with locks and everything. This isn't necessary, it's just an accident of history that nobody has gotten around to changing.
For example:
Rearranging the column order (or inserting a column) should just be an instant metadata update. Instead the entire table is rewritten... synchronously.
Adding NON NULL columns similarly requires the value to be populated for every row at the point in time when the DML command is run. Instead, the default function should be added to the metadata, and then the change should roll out incrementally over time.
Etc, etc...
Whatever it is that programmers do with simple "objectid-columnname-value" schemas to make changes "instant" is what RDBMS platforms could also do, but don't.
You mean just like mysql, oracle, sybase and mssql do ?
why and how of the single table design approach
strange or completely a-typical for 99% of web apps?
Not sure what web apps you've worked on but the rest of the world doesnt default to anything like this. Even if it does make sense for the usecase, even Reddit only evolved to this much later.
For example, one can implement role-based ACL on a tree structure in metadata tables, with one data table. Then sql can be used to get permissions, and even join on the data table, if that works for you.
SELECT TOP 50 * FROM [things] [post]
JOIN [things] [category] ON [category].[id] = [post].[parent_id]
WHERE [post].[type] = 'post'
AND [category].[type] = 'category' AND [category].[slug] = 'animal-pictures'
ORDER BY ([post].[child_count] / DATEDIFF('hh', [post].[created_date], GETUTCDATE()) DESC;
Basically, you have tables a bit like these:
- classifier_groups (e.g. product_classifiers, basket_classifiers)
- classifiers (e.g. product_types, discount_types, delivery_methods, payment_methods)
- classifier_values (e.g. regular_product, bid_product, timed_discount, loyalty_discount, postal_delivery, courier_delivery, credit_card, paypal)
- classifier_value_attributes (e.g. product_name, product_weight, product_size, bid_start_date, bid_start_value, discount_start_date, discount_percentage, ...)
- classifier_value_attribute_values (e.g. "Some product name", "0.25 kg", "2022.08.10 09:00", 5 EUR)
Though sometimes the approach folds in on itself and the attributes are classifiers/classifier_values themselves, or JSON is used, or more tables inbetween are used when you need to track where a particular usage is needed (e.g. when you define a template and then have an item that is based on the template but with changed data).So the end result is that instead of 200 tables you have just a few instead, but the problem is that you can't really figure out what is happening with just foreign keys (especially when you are trying to do the reverse - refer from these classifiers to another table, since clearly you can't have a foreign key there and instead you do the EAV thing, like "link_type"/"link_table_name" and "referenced_id") and oftentimes you can't really use the DB because the enums and other data that you need to be able to write queries is actually stored in the application code.
Regardless of what you call it, the thoughts on the approach, or at least its components seem split, even back in the day:
1) https://tonyandrews.blogspot.com/2004/10/otlt-and-eav-two-bi...
2) (PDF) https://novicksoftware.com/wp-content/uploads/2016/09/Entity...
3) https://softwareengineering.stackexchange.com/questions/9312...
I've seen some people swear by it, though personally I really dislike it, since any DB schema visualization tool just turns up a black box and a dozen JOINs across these classifier tables will always be less clear than just referencing tables like products, bid_products, timed_discounts, loyalty_discounts etc. So personally, I'd much prefer the 200 tables with foreign keys between them wherever necessary, with really dumb model bindings in the app instead of a bunch of enums, complex service logic and inevitable orphaned data. And yet, somehow people fear the idea of hundreds of table, but would prefer to shove this functionality into bunches of data instead.
(disclaimer: domain is made up so perhaps not the best example, also a proper term for such a pattern escapes my mind at the moment)
In other words, you've manually developed a relational database on top of a relational database that you're using as a file system.
Additionally, forcing things into a correct schema also protects you from a lot of data inconsistencies out of the box.
Finally, the dbms is going to be far better at JOINs than your application will. Nearly every web application needs JOINs at some point. Developers just don’t recognize what they are doing so they don’t realize what they are missing out on by doing it at the application layer.
Anyway - Schema slows development as hell, you need to maintain mapper layer between domain models and db models unless you model your system with anemic model mixed with tech stuff(db), but it is mess
Additionally you deal with either stringly typed sql
Or ORMs that require months of practice to be proficient even in c# which has LINQ
Because eventually, you'd want to analyze that data and it's a huge pain to do it with NoSQL. Imagine if you hired a business analyst and she needs to look at the data. Are you going to expect her to learn Javascript to query the data? Are you going to write an ETL pipeline to move data from a NoSQL db to an SQL db?
Note: I know many NoSQL DBs now support SQL queries.
I've set up databases, I've broken databases, I've restored databases, I've scaled databases, and I've migrated them. Never lost so much as a nibble of data.
My introduction to NoSQL was an article about Mongo losing someone's production data. Not even all of the data - partial data loss, the worst kind of data loss.
I'm just gonna head off that massive headache at day 0 and use an ACID compliant database.
From there it's lack of experience. Same reason I wouldn't decide to write my next thing in a new language unless I was specifically learning that language.
Ppl hate nosql cuz of mongo when there are other dbs, e.g RavenDB
>I'm just gonna head off that massive headache at day 0 and use an ACID compliant database.
It is just ACID vs BASE
I also have no reason to learn it at this time, an SQL database wins uncontested whenever I need to store data.
If I was to start a new project I wouldn't pick that moment to learn a new programming language. Same thing, different part of the stack
Honestly what it'd take would be the next WordPress or whatever using nosql by default. Make it need learning
It was a first impressions thing that stopped any further investigation, not a comment on the current state of NoSQL
Jepsen