I'm interested in becoming more familiar with functional programming as a paradigm, so I'm trying to introduce a more functional style to some of my projects. I'm struggling to understand how to handle side effects with a database.
I have some functions that kind of look like this:
db query + db query | + | | v | +--------->a() v | f(type)+--+ | +--------->b()
The trouble is that both f
and a
are non-pure functions because they need to do database queries. I've seen some functional projects that work by having all the state in a single place and the rest of the application takes bits and pieces of state as function parameters. I can replicate something like that here by putting all the queries in f
for example, but since b
doesn't need the database queries used by a
, this would be really inefficient.
Is there a pattern for handling database access in functional programs?
f
as a parameter? In most of the cases it is not significant, especially in cases where you can load data asynchronously.SELECT
statement returns data from the file system, which can be updated between select statements.SELECT COUNT(*) FROM MyTable
returns99
. Next week, same query(with same arguments as you said)SELECT COUNT(*) FROM MyTable
will return120
. With pure functionsum(12, 30)
returns42
today and next week it will also return42
. With pure function I can save final result and never call this function anymore for arguments12
and30
, but I can not do it for SQL statements, I need to execute actual sql statement again."SELECT COUNT(*) FROM MyTable"
string to the database and receives different results at different time, which is the case for OP's example.