In this episode, we explore data access in Rust web application development, focusing on how backend applications interact with databases to store, retrieve, and manage information. Data access is a critical component of modern web applications. We examine the architectural concepts and implementation approaches involved in connecting application logic with persistent data storage while maintaining clean, organised, and maintainable code. Through this lesson, we explore how Rust developers can structure data access operations, manage database interactions, and establish a reliable foundation for building efficient backend services. Whether you are developing REST APIs, SaaS platforms, or enterprise web applications, understanding data access is essential for building robust and scalable software systems. What you'll learn:
Understanding data access in Rust web applications.
Connecting backend applications to databases.
Structuring database interaction logic.
Understanding data retrieval and persistence.
Organising application and data access layers.
Exploring database integration patterns.
Building maintainable and scalable backend systems.
Audio and video play straight from the show's own hosting. PodSubs stores and serves no media.
Transcript
From the show. Tap a time to play from there.
Speaker 1Building a TodoMVC from scratch with Rust as a backend, Postgres as a database, and native web components for the frontend. Okay, let's go. Now in this project, we are going to have two parts. First, the frontend with our package.json. And for now, we're going to keep it empty like this. We'll do the frontend later. And then we're going to have our backend with our cargo2ml. First, we're going to have our Tokyo. for everything which is going to be a sink. We'll be using some future trait as well.
Speaker 1And then we're going to use this error that we remove quite a bit of boilerplate for errors. Then on the JSON lead side, we'll be using the silly crates. On the web leads, we'll be using warp. And then on the DB leads, we'll be using SQLX for DB executor and SQLB, which is actually a little experimental SQL builders that I've been writing but this is completely optional here. Okay, so now we're going to create our source main.rs, very
Speaker 1simple hello world. And for now we're going to mute the warning as we're going to build the code and then eventually we'll comment this out. Press save and then backend folder, we do a cargo run and run our hello world. So far so good. Okay, so let's focus on this file only here for now. our application, we're going to have three main modules. And that is going to be the mode model, which is going to be our model layer or data layer in a way. And
Speaker 1then we're going to have a mode security. And then we're going to have a mode web. That is going to be the three modules that we're going to have. And for those, we're going to create a folder for each one of them, because we're going to have more than one file. So we're going to have model.mod.rs. Then we're going to have security. mode dot RS. And then we're going to have web mode dot RS. Focus on is our model layer or data layer. And we're going
Speaker 1to create here readme file, where we're going to put our command line. And so for the database, we're going to use our Docker run, we're going to use default Postgres port. And then the password of the Postgres users, the root users will be Postgres. and then we're going to use Postgres 14. And then eventually, optionally, we're not going to really use it here, but we can, in another terminal, do a docker command like this, such as we have a psql command on this database. So now that we have that, we're going to copy this, add
Speaker 1a new terminal, name it netabase, such as we don't get confused later, and then here we paste this command line. And that will create a database here that we can connect to. And now we can go back to our command line here. So now we're going to close this file, we go back to our backend, and we're going to create our first sub module, which will be just a DB here. So the first thing we're going to do is define the type for the database. And so the type here will be just a type alias DB, which
Speaker 1will be the pool. And that will be a SQLX object of Postgres. And both of those are SQLX types. So we're going to import them here. into our application. So the first thing we're going to do is create a new method, a low-level method just for this module, which is going to create our new DB pool. It's going to take the host, the database name, the user, password, and the max connection. It will return the result, DB,
Speaker 1and for now it will return the error of SQLX. We're going to create our connection string This is the way that SQLX works. Format is going to be Postgres, the user, the password, the host, and the database. User, password, host, DB. And then we're going to use a PGPool option from SQLX to create the database pool. We are going to give the max connection here. And then the timeout will
Speaker 1be hard-coded to 500 milliseconds. and then we give our connection string. Press save, and everything should be fine. Now our application will not call this method directly here, that will be too much information for the rest of the code. So we just have a pub async fn init db. That will actually recreate the database all the time, but obviously in production, that will just create the appropriate database pool such as can be used in the rest of
Speaker 1the code. It's going to return result, DB SQL X error. And that will just call new DB pool. And because we want to be a little bit organized here, we're going to have some constant to define the root DB properties for now. And then later, we're going to see how we do the application one. And we're going to add those here to the function parameters. For now, the max connection pool here will be one. So now we're
Speaker 1going to do our first unit test. So it's going to be a blank one for now. So it's going to be the config test, obviously. We're going to use our init method, the public one, for now only. And then we're making sure that we're using Tokyo test, because it's going to be async. And then the convention here, which will make more sense later, is repeating the module path here. So we have module underscore db, underscore the name of the function, and then eventually they could be also suffix. to have the different states of the test.
Speaker 1And now we're going to run the test, but for that, we're going to use cargo watch. So we're going to have a cargo watch, dash Q for quiet, dash C for clear, dash watch, we're just going to watch the source folder because we're going to change other files and we don't want to restart the server all the time. And then we have the dash X for execute. So that will do a cargo test. That would be our filter. So that's the reason why we have this naming convention.
Speaker 1You can have your own strategies. That's completely fine, obviously. And then we're going to have two other parameters, which you have to give with dash dash. One is to make sure that we have a thread one. And that is because we have all these database and we're going to create and recreate database. And so to make sure that thing doesn't work on each other, We're going to run them as a thread one. Making them multithreaded is possible, just more work. And for now, we're just going to focus on that. And then the next little trick here
Speaker 1is to have a no capture for just development. And that allows us to have some println so that we're going to see what we're going to test. And then we replace the println by the asserts and then everything is tight. I'm going to select this and I'm going to copy paste here. That should run completely fine. And it's normal because we do not have anything here in the test. So this one has to succeed, but at least everything is compiling fine. And now the only thing
Speaker 1we're going to add for now is just this initDB. And if it doesn't fail, that at least the connection works. So we're going to press save and everything pass. One personal preference that I have is to have the unit test in their own files. It's clearer for me. So the way that I do that is I take the content of the test and I'm going to create a folder here. And my convention is I'm going to put them under test. And then the name of the file is going to be again a flat name, model underscore db.rs.
Speaker 1And then I put my test here. And then the trick here is I go back to the db and Rust has a cool attribute. which is path. And then I can put a relative path like this. Mondeo underscore DB dot RS. Now I press save. And everything runs as before. But now I have my cool underscore test folders where I'm going to have all my tests. Sometimes I might put them into a hierarchical kind of folder structure.
Speaker 1But at the beginning, I like to have them flat. It's very easy to see what your test. And again, because the test convention here, we're always repeating the module tree, then I can test very easily whatever module tree I want. Okay, so now it's time to create our SQL database. So the way that I like to create it is with SQL files. So what we're going to do is we're going to create a folder, SQL. And inside the folder, we're going to create the first file here, which is going to be 00. And we're going to order them
Speaker 1like this, recreate DB. And by convention, the 00 is going to be run as a Postgres root. We're going to first drop the database and we're going to call our database appdb and we're going to drop the user. Again, this is only for development, obviously. And then as it matures, then you don't have this way. You have an incremental way of doing with the schema that you have in production. But for early development, this is very, very fast. And then obviously create the user app user with any password
Speaker 1you want and then the appdb and now we have our first recreate db sql file and the second sql file that we're going to create is going to be a zero one create schema and we will run that as the app user first we're going to create a to do status enum as a Postgres enum with open and close. And then we're going to create our table to do with the ID, which will be our serial number here. And CID and CTIME, by convention, the CID
Speaker 1will be the user ID of the person that have created the to-do. And the CTIME is a time of creation. So here we are just going to default it to now. And it won't even have to be part of the Cloud API. And then we have the title. And then we have the status with the enum that we have just created. And that would be a not new. And the default will be open. Now a little trick here, we start all our IDs, the ones that are here, we're starting then at 1000. This way here, when we
Speaker 1do unit tests or whatever, if we are below the 1000, we know that when we create it with that ID, it won't overlap. In this episode here, we're not going to really create the user table. We should have a user table with the CID, but for now we just have that such as we can show the pattern in the code later. And now the last file that we're going to create is going to be more kind of a dev file. And that will be our dev seed SQL. The first thing we're going to do here is create a first to do. And again, we're creating with an
Speaker 1ID below a thousand, such as it doesn't overlap with the sequence number. And here we're going to specify the status and we're going to make it close. And just for the sake of it, we're going to insert another one. And this time, we're not going to include the status. So that will take the default status. And the convention here is the title will be just to do and the title ID, such as we can write our unit test like this. And now we have all the SQL file we need. Now we go back to our DB
Speaker 1file here. We're just going to focus on this file for now. So now we want to create a function that will execute our SQL file. The first file will be executed as a PG root. And the two other files will be executed as our pgApp. So it's going to be relatively simple. We do our async, fn, pxec, it's going to take a db, and then our file, which will be just a string. It's going to return result, void, if it's OK, otherwise our SQLX error. We're going to
Speaker 1return the OK state to make sure that it compiles. So the first thing we're going to do is Read the file. Very simple. We'll use a read to string function from the FS module. We're going to make sure that we import it. And then we're just doing a map error to print the error message in a nice way. And then we just cascade the exception back up. And so this is why we have the question mark here. So this will return exactly the same error if there
Speaker 1is one, which is a SQLX error. Then we're going to split the SQL files in SQL statements. So that would be a vector of STR. And we're going to do a Pullman splitting right now, which is going to be a content split on semicolon. And obviously here, you might want to do a little bit more sophisticated because if you have other semicolon as values or comments, it will break. Okay, so now we are ready to do
Speaker 1the iteration on our statements. So we're going to do a for SQL in SQL S, which is our array. In SQLX, the way you execute a statement is with a SQLX query. You give the SQL string and then you call execute with your database pool. And you call await because it's async. Now what we want to do here is each statement, if there is an error, rather to stop, we're just going to print it in. Again,
Speaker 1this is for development. And in production, again, that might not be the right way. So we're going to do a match. If it's okay, then we're happy. So we're going to return void. And if there is an error, we're going to print and just a warning, p exec sql file failed. And then we're going to give the cause, which will come from our sqlx. The file ex, comma, and then that's it. Press save. And everything should compile.
Speaker 1Now that we have that, we can close this function. And we're going to focus on our initDB. And we're going to define some other constants here. The first ones are going to be the appDB information here. So all of these ones. And obviously that will come from probably config files or environment variables if you deploy on Kubernetes. But right now we're just putting them as constants. And then the other set of constant we want is our
Speaker 1SQL dir, which will be our SQL folder, and the SQL recreate, which will be the only files that we run as a Postgres user. Now that we have that, we're ready to implement our NEDB. So this last line will actually be returning the app DB. But for now, we're going to keep it as pgroot, such as we compiled and everything run nicely. And then the first things we're going to do is we're going to create our application database. And so for that, we're going to have
Speaker 1our root DB database pool, which we create the new pool here. And we just need to have a maximum connection of one. And then we're going to call our P exec. We just created with the database, the root DB and the SQL create. So that will create the user and the database. Press save to make sure everything works. So far so good. Now we can return the pgApp rather than the pgRoot. So here we're just going to change this pgApp and the mass connection, we can use
Speaker 1our constant. We're going to press save and everything should compile and everything works here because we have a valid connection to this new AppDB pool. So we didn't create the schema. We're going to do that now. Run the app sql files and for this, We're going to create an app DB. So just copy this one. We're going to copy that here. Just by app. And that will be our app DB. And this is just connection pool
Speaker 1just used to create the files, to execute the files. Then we're going to read the directories, the SQL dir. And we're going to iterate. And we're just going to extract the path. So that allows us to not have too many kind of enum, nested enum. And that will give us a vector of path buff. We have our path mute because we actually want to sort it to make sure we have the SQL file in the right order. So that is our best practice. And then we're going
Speaker 1to execute each file. So we are going to iterate through all the paths, the path buff that we have. Then if it's a valid path, a valid string, We need to accept only the. sql and not the recreate. So for that very easy, we do a path if path ends with. sql and path not sql recreate. And
Speaker 1then we're just going to call our p exec, app db and our path, which is a string now. We're going to await and we're going to do question mark here if there's an error. We'll stop everything, which usually most of the error will be kind of swallowed by the P exec, the way we coded it. And we're going to press save. We forgot to import the path path. We're going to press save and everything should compile and
Speaker 1everything should work because we didn't change anything. We just executed some files. So our SQL files are valid and we're returning now the app DB. Now, if we go back to our model underscore DB test, we can do a very simple test. So our best practice here, that is the action of the test. And the check, we're going to be a very simple check, which will be result equal SQLX query. So that's the way SQLX works.
Speaker 1And we can do a select star from to do. We're going to fetch all. And that will return p zeros array. of our DB. We're going to await with full error if there is one. And then we want to have an assert. And we're just going to check that we have two to-dos. So far so good. Result, length, number of seed to-dos. This is our message to make sure we know what we tested. Press save. We got
Speaker 1a T. Press save. And then boom, everything works. It might look a little bit over complex, but actually when you start like this, you have a very fast way to iterate through your code because now you can change your SQL files, press save on your RS and everything will be recreated and your test will be rerun. And we'll see how later this is going to be very convenient. Okay. So let's do some real work now. So we can close these files. and we can go to our model
Speaker 1mod and we're going to create a new mod now which is going to be mod todo and that will be for todo.rs module file press save and everything should work we can probably stop the CargoWatch for now, and we'll restart it later. So now we're in business. So first we're going to create our to-do object. So it's going to be a public struct, to-do, and we're going to have ID as 64, which maps to the big
Speaker 1int in the database. Our pubcid, which is also big int, that will be our creator ID, and then our title, which will be a string. it will have to be on obviously one thing i like to do is to create region and so this one will be the to do types so like this i can collapse the code like this and kind of have all my types here and then collapse them press save now we're going to add some derive and the first one we're going to
Speaker 1do is called sqlx from row and that will allow sqlx to make this magic when we do a from or fetch, then SQLX will do the magic and will return this structure here. So it's very convenient. And we're going to make it debug as well and clone. For now, we're not going to have the status. We'll show how to do the status later. So then after, we're going to have another region, which will be for to do Mac. And Mac in our world here in our pattern is
Speaker 1model access controller. It has a similar pattern as a DAO, but it's using the Rust construct here. which means that they don't really need to be object. They can just be a struct with some associative function. So for that, we're going to have our pub struct to do Mac. Doesn't have to have any properties. And then we're going to implement our first cross method, which is going to be the list. So we do a pub async list, and that will take our db, which we import, and
Speaker 1it will return a Vect, of to do and for now it will return SQLX error. First thing we do is we create our SQL query. So select that will be for now a row query, CID title from to do order by ID decreasing. That will order reverse, which is usually what you want for this use case. Then we're going to build the SQLX query object. And that
Speaker 1would be with query sqlx query as, and we do the turbofish here. This one can be deduced by the compiler. And then we're going to give our to do. And we're going to give our SQL string. And then we're going to execute the query. So the way it works with sqlx is you take the query object and you do a fetch or db and a wait. And here
Speaker 1I'm going to toggle the types inlay from Rationalizer. And we can see that we have a vector of todo because here we say query as, and we gave in the TurboFish, we gave the todo type. That is the way SQLX is coded here. And we can do a fetch all, which return a vector, or a fetch one, we'll see later, that return only one. And now we can return our todos. press save, and everything should compile.
Speaker 1Or at least, Rust Analyzer didn't complain. Now, in fact here, because we returned the vector of todo, the compiler will have enough information once we have this statement here. So in fact, we can remove the turbofish, press save, and everything should work. And if I toggle the type in Lays, I will see the compiler deducted that was going to be a todo type. we're going to use the same pattern that we used before which means that we're going
Speaker 1to put our unit test in another file here which will be inside model to do dot rs which is going to be a model to do dot rs so we're going to create our first test very simple we do our tokyo test we have our model underscore to do underscore list to follow our best practice as a fixture which is basically the setup of the test. We are going to have our DB. The action of the
Speaker 1test will be to call the TodoMac. Mac list with the DB and the await. We're going to make sure that we import the initDB and then we import the TodoMac. And then for now, the check will be a very simple check, will be assert equal for now we are just going to check how many items which will be two we're going to press save everything should compile and
Speaker 1now we are going to do our cargo watch but rather to have our model underscore db we're going to have our model to do and we can do the list but then we'll keep it this way and then we'll see how it goes as we add more tests we're going to press save and boom sometime it's almost good to be true what we can do is a println we're going to have this way looks better and
Speaker 1then it's going to be the debug and we do our to do's press save and then boom we have our two to do's here it's coming from the database so obviously we can remove that and we can add more tests so for example we can test the to do 101 which will be the first since we go from last to first, and then we can do the test for to do one zero, which should be something like that. Now we press save, and everything should pass,
Speaker 1and everything is tight. So here we created the test data in the SQL. That is a strategy that can be debatable, but it's just to show the context. You might have here in your method, having an init DB or a seed test DB, and then testing this data from the test rather than something from the outside. But this is a gist of it. So this is pretty cool. But there is one thing here that is not optimum, is that the list actually is for a SQLX error.
Speaker 1But we might want to wrap it into our own error. Because sometimes we're going to have module specific errors. And so we don't want to rely on everything being an external libraries error. It would not match. And the way we do that is we go back here and pattern that I'm following. And we're going to use this error, which is going to allow us to remove quite a bit of boilerplate. And in this case, I'm aliasing it to this error because the error will also be called error.
Speaker 1So I don't want it to overlap. It will actually work because it's just a macro, but I feel it's cleaner this way. So then after we have our pub enum error, so that will be our model error. We derive this error, and we're going to make it debug as well. And then the way that this error works is you create any invariants, and you can annotate them like this, with the error transparent. And then you say where it comes from, and you give a name here.
Speaker 1And so that allows that when we do the question mark, the Rust compiler will do the right things because this error macro will create all of the right transformations. So now we can also do one for IO errors. And those will be the two errors for now that we want as a pass through. Pressing save, everything should be fine. Okay, so now we can go to our model. And then we're going to use the create model. And we can
Speaker 1replace this by model error. Now if we press save, everything should run exactly the same. Because we didn't test the model error, so everything should be fine. Okay, so we have our list, and now we're going to code our create function. So very similar, we're going to have a pub, a sync, a function that will be create, we'll take the database, same signature, all of the create function will have the same base signature, and as the data,
Speaker 1we could do to do, but that wouldn't really make sense because we do not want the create to take the ID, obviously. So we're going to create a new type, which will be a data patch, we're just going to do that after. And that will return the real to do and with our model error we just created. And so what we're going to do here is we go back up. And we're going to create our struct to do patch. And the concept here is to have the
Speaker 1patch values. So it will be option because everything will be optional. So We'll have the pub CID, which would be an option of I64, our pub title, and that will be an option of string. And now in our create function, we're going to create our SQL statement, let SQL insert into to do and that will be the CID and the title for now values The best practice
Speaker 1we're going to follow is we're going to use prepare statement for everything, and then we're going to return the ID, the ID, the title. And the way that we're going to do our query with sqlx, we build our query, sqlx, query as, the TurboFish, the first one the compiler can deduct it, and then we're going to have our to-do, we pass our SQL. And then the way it works
Speaker 1is we call the bind one, two, three, four IDs for the CID. That is a CID. Yes, it's not the ID. And then we're going to bind the data.title unwrap, we're going to return the title. And that is just for now, because later we're going to see how we're going to optimize it and make it much more dynamic. And then after what we're going to do is And let to do query dot fetch one. This time we
Speaker 1pass the DB, the await, question mark, and then we return the to do. We press save, everything should compile. And now we can go to our model to do test. And we're going to create a test for our create. So we're going to do create. The fixture will be the same. So we're going to have the database and we're going to have as a fixture, we're going to
Speaker 1add our data fix FX, which is for fixture. That's the little convention I follow and is going to implement the title and the default. Actually, we might have forgotten here to derive with default and clone. Now we go back to our test. We're going to do the action of the test. Very simple, to do create the DB and we're going to clone the data fixture such as we can use it later. And then that will return
Speaker 1the to do created. And as a check for now, we can just println empty line, simpler to spot on debug. And then we have our to do created. Press save. We forgot to import this one. Press save. And now everything works and we have our data here. So pretty neat. So obviously we don't want the printed in and we're
Speaker 1going to assert the value. We can make sure, for example, that the to do created ID is greater than or equal to 1000. So that is what we've done in our database. And then we're going to check the title from the fixture with the title that we just created. Press save. and everything should pass. Okay, so one thing we didn't do is to implement the status of our Todo. And it's a custom type, so we need to do a little bit of custom work. So if we go
Speaker 1back to our Todo.rs, we're going to create a pub enum Todo status, and that will have open and close. And the design here is just to put it back here, status, and also on the patch, like that. Now we need to annotate the to-do status with couple of annotations. So the first one, we need to tell SQLX that that is a type. So the way you do that is SQL type. We're going to have debug, clone, and also
Speaker 1partial EQ and EQ. And that allows to do the equal and comparison. Then we need to tell SQLX to map this to the database enum that we had created in the SQL file. And for this, we use the SQLX macro with the attribute that name, and then we pass this value. And that is the name that we had in our create schema.sql. And lastly, here we're using uppercase to follow the Rust convention, but in our schema, we're using the lowercase. So SQLX has another macro for that,
Speaker 1and we can rename all of the variant lowercase. And that will put everything lowercase. So now what we need to do is to make sure that when we're getting the data back from the database, we are going to add this, the returning. So in the create, we need to add status because that is needed to be able to create the to do object. And the same thing here, when we do the select, we need to make sure that we return status as well. The other doesn't matter.
Speaker 1SQLX will find its duck. So now we press save. and everything should work as before, but with a status. So this means that now if we go back here in our test, we can actually do an assert equal. So the data fixture is going to be none, because it's going to be the default, we're not setting up. But in the database, we have default of open. So here we can have a to do status, open, we
Speaker 1import the crate. And we're going to compare it to the to do created the status. Let's save. And it's almost too good to be true. Everything is working fine. So now if we go back to our to do dot RS, there's a couple of things that we can do better. First one here, that is a big one. This should come from user context. And we're going to see later with the security layer, how we're going to add user context to these methods. And then what we
Speaker 1need to fix as well is a SQL segment. Right now we're using static string and this obviously doesn't really scale because for example, we just added status to to do patch. We had to add this to our select here as well. And in fact, we're not even taking it as we are creating the object, even if it's part of to do patch, we're not creating it here. So you have two ways of solving this problem. One is by using an ORM, like for example, DSL or something like that, and that will tie your data structure
Speaker 1to your schema, which might be an option if that is your pattern. The other one is to use a SQL builder that gives a little bit more flexibility of mapping your SQL queries that you build with a builder pattern into your struct. And that is what we're going to use today. And actually I'm creating one right now and it's still in experimentation phase. It's called SQLB. But again, this is completely optional and you can use whatever libraries you want. So the way it works is rather to
Speaker 1do the query like that. What we're going to do is create a variable, sb sqlbuilder, which will take our sqlb insert. The table will be to do. The data will be data.fields. And we're going to see later how we can make sure that to do patch implement that. And then the returning will be an array of string that needs to match the to do structure. That will be ID, CID, title, and status. And then that will
Speaker 1return insert SQL builder. And our insert SQL builder has a similar interface and SQLX query. And that is fetch one. So that will work the same. And we can toggle the inlay off. And so to make sure that data implement fields, there's a couple of things we need to do. First, any member needs to be bindable to SQLX. And by default, I64 and string and all of that are. But since to-do status is a custom type, We just need to
Speaker 1add something else. And that is our SQLB bindable macro, which basically will make sure that the to-do status has the right implementation to be binded as a SQLX value. Now that we have that, we're going to back to our to-do patch and we're going to add another macro, which is going to be a SQLB fields. And that will give the information to the SQL builder about the properties. It will only get the values that are defined. like this a patch will be a true sql patch now
Speaker 1if we go down here we're going to make sure that we're going to import the trait as field now before we press save we need to make sure that the data has a field cid because remember before we had it hardcoded so what we're going to do is make sure we go to this place and when we have our data fixture we'll add the CID just for now. We're going to change it later actually. And we go back to our todo.rs, press save, and hopefully everything works.
Speaker 1Now we do not want to have todo patch having the CID because the CID should be a matter of the model access controller and the caller should just pass the user context by our design and shouldn't have to pass all of this administrative data, which is a creation time, the creation ID, and then later the modifier ID and the modifier time. So the way we're going to do that is first we're going to remove the ID for the to do patch. So that will prevent anybody to
Speaker 1pass it as a value. Now we have the compile error. So we're going to have to remove that from here. And we go back to our to do dot RS. But now we need to make sure that we're creating it. And that is where power of a SQL Builder is, I can have a model like this, where I have a mutable fields, And that will be the data fields. And I can add a new field. And the way we add is with a topo. The first one is a column name. And the second one is a value.
Speaker 1So here we're going to hot cut it. One, two, three. Then we pass into. And now the data, we're going to pass the fields. And we press save. Command option save to save all the files. And then boom, everything passed. So now we are going to remove that. Press save. And then we can use our SQL builder here. So rather to do that, we're going to have a let sb equal sqlb select. The table will be to do.
Speaker 1And the columns will be the same as above. And now rather to call the query, we can just do a sb fetch all, has the same name. And we press save. And everything should work fine. And it doesn't. And that is the cool thing about the unit test. We just realized that we didn't do the order by. So if we go back up here, we are realizing that actually the order by doesn't match. So now what we can do is order by. And the way that
Speaker 1right now SQL B works is we do exclamation mark for descending and then ID. Press save. And then boom, it works. Now we can remove that. So this begin to looks pretty good. Now, one thing that's going to be fixed is this hardcoded value. And the pattern we're going to follow is that any model action controller will have to take the user context, which will have the user ID at least in it. And that will be the responsibility of the security layer to make sure to
Speaker 1create the right user context. And when we're going to have a web layer or even some asynchronous job layer, that will be from a token. And so we can move to our security file. We will be creating our module error later. So I want to make sure that we have that. What this security module will export for now will be a struct. And it's going to be very simple for now, but after you can make it more and more advanced. So it's going to be a user CTX. And for now, we just have a pub
Speaker 1user ID. And we won't even have the user ID in the database for now, but we'll have everything ready, such as later, it will be piece of cake to add it. And so now what we want is a method, which will be a sink because he will need to ask probably the database or some services on the backend. And that will be a UTX user context from token. The token will be a string. So later that will be a HTTP only token for the browser. And it
Speaker 1will be a result user CTX. And we're going to implement the error of the security module here below. So now on this module, we're going to put everything into mod.rs. But later, as we're going to add more code, that might split in our other files. But right now, we're going to put the error here. So that would be our error enum for the security. And inside, we're just going to have our custom enum, which is going to be invalid token. And right now the validation is going to be very, very simple. So we're going to do
Speaker 1a match token, which is a string. We're going to parse. We're going to specify the TurboFish that will give the type information to the method, such as it can know which type to parse to. And then if it's okay, we're going to return the okay of userctx, userId. And then if we have an error, we don't really care what it is for now. And we're just going to return an error, which will be our error below. Invalid token.
Speaker 1Press save, nothing to change because nobody's calling it. But now what we can do is add the user context to all of our to-dos. The way we're going to do that is here, UTX. So the convention is we're going to use UTX for user context. And that will be a reference. of user context. Then we're going to do the same thing for list. Because in fact, later, we will use the UTX as also access control. So
Speaker 1having the access control at the data level makes the whole application much safer. And obviously, our test doesn't compile anymore. What we're going to do is as part of the fixture, going to have a let UTX equal UTX from token and 123. Don't forget to put the await. And then we need to make sure to call our method with a reference of UTX. And we're going to do the same thing for our to do list. And here again,
Speaker 1reference of UTX command option save to save all the files, everything runs and everything works. So it's pretty cool. a little first security layer, almost nothing, but at least the structure of it, and all our tests are working fine. Okay, so we're going to go back to our to do dot RS. And we're going to finish our CRUD API. Before we do that, there's one little thing that we can make it a little less redundant. And that is the table name, and the columns. So the way we're
Speaker 1going to do that for now is going to be using const. It's going to be very simple. We're going to do a TodoMac. We're going to put it in another block, just to be clean. And then in bigger projects, you can even have your TodoMac, even if it's not an object. Your TodoMac struct can implement associative function trait. And that will allow you to have more flexibility down the road. But for now, for this size of project, having a const table, and that will be a static string,
Speaker 1and that will be for Todo. And then for the columns, we are going to do very similar. So that will be our columns. The type will be a static of static strings. And the values are just going to be these ones. And now, rather to have to do table, we can have self table. And here, rather to have this, we can have self columns. We can do the same thing for the list. And now we can press save. And everything should work exactly the same. So now we
Speaker 1can create our get method, which will be a database, takes a DB, we're going to do underscore UTX, because we're not going to use it for now, just UTX. And now it's not going to be the data obviously, it's going to be the ID, which is going to be i64. Result, to do, and the model error. Very similar, sb equal sqlb select dot table, self-table.columns, self-columns, and then
Speaker 1we're going to use the and, where equal, the column name, id, and the value, id. Now we get our to-do, so we're going to do a let, to-do equal, dsb, and we're going to do the fetch one, the db.await, question mark. And then we're going to return our to-do. Press save to make sure everything compiles. And we'll do the unit test a little bit later for this one. And now
Speaker 1below we can do our update. It's going to be very similar. We do our update. We're going to create the SB. And so the update is going to take the ID and the to do patch. So very similar. We do the update, the table, the data dot fields. Then on this time, we're going to do the where as well. we're going to do the returning we're going to execute this is going to be a let to do equal sb and it's going to be the same
Speaker 1one here and then we're going to return the to do press save and everything should compile so now we can go to our model to do for the test so we're going to add one for the get and for the get same fixture and then the action here for now but we're going to just query the one that we have in our dev seed. So we're going to do a let todo, and we're going to do a todo mac, get our db, our utx, and the id will be 100. That is the first one, which
Speaker 1is the latest one in the list, dot await, question mark, and then we can do our check. We're going to check that the id is 100, and we can test also the title, and we know that the title is going to be todo 100. the status is actually close on this one so we do to do status close status press save and now we have the tree test
Speaker 1and the to do create is okay so everything is looks pretty good okay so now we're going to create our to do update test and we're going to suffix it with okay we're going to see why later and then we're going to add our fixture. So we're going to do the unit DB, the UTX, our data fixture. And then we're going to create our new data as a data fixture. And then we're going to prepare our update data fixture. Then we're going to do our action, which is the update. And we're going to give the
Speaker 1update data fixture. we're cloning because we're going to use it in the check below. And then we're just going to do some minimum checks here, which is we're going to query the database again. And then we're just going to make sure that we have three and then check the ID and the title. We're going to press save. Now we should have four tests. And now we have the update. Okay. So far so good. Now the reason why I have update okay, is because in fact, here I should have the get okay which is when we
Speaker 1do a get with a good id what happens if we do a get with a bad id so for example we are going to copy paste our get and we are going to call it wrong id and then we are going to pass an id here which is going to be 999 and because we want to test that it fails we are going to get the result we are going to remove question mark because we don't want to fail if it fails because actually it should fail and for now just to see what we get
Speaker 1we're just going to do a println of the result we're going to press save we should see five tests and we see our row not found which is actually a sql x error So it does make sense, but we can do a little bit better because in our code, when we have this kind of error, we really want to know which kind of entity it is. And this is why we wrap SQLX into a model error, such
Speaker 1as we can have our own errors if we need to. So to do that, we're going to go back to our mode for the model. And we're going to add a custom error, which is going to be Entity not found. And it's going to take the entity name, which is a table name. It will also take the ID as a string. And here we make a string such as if later we want to have other type or compound IDs, everything will work fine. And with the this error package,
Speaker 1the way you do it is you annotate it with error and then the message you want to have. So we are going to say entity not found, the entity type, and then the entity ID. is the first parameters and the second parameter. Press save, everything should be fine. And obviously, we still have our SQLX error. Now if we go to our to do, rather to do the question mark, which will basically return the SQLX error, which will be wrapped into a model error, what we want here is
Speaker 1defer the question mark in a way. And we're going to do a map error, which we're going to map the error we'll get a SQL x error, and we'll match it. And if you match the SQL x error, rule not found, then we're going to return our specific error here, which is going to be our model error entity not found, we give the table name and the ID to string. And if it's an author, SQL x error,
Speaker 1which is not rule not found, then we're going to wrap it into our model error as a SQL x error variant that we had before. Now we don't forget to do the question mark. And here we could just return that but we're going to do this way. We're going to press Save. Everything should compile. Now, as we have seen, we have our error, which is now entity not found to do 999. So that is useful information
Speaker 1for debugging later. So if we go back to our model to do, and we have the wrong ID, we can remove the println. And here's the way we're going to test it. We're going to match the result that we got here. And if it's okay, that shouldn't be okay. So we're going to say shouldn't succeed. And if it's an entity not found, which is what it's supposed to do, we're going to still check the type and the ID. And if it's another model error, we're going to say
Speaker 1that we got the wrong error. And we say, which one? We're going to press save. And here we haven't imported the model. So we import model here. Press save. And then everything should work fine. So that is nice. But if we go back to our to-do implementation, we're going to want to have the same logic for update. And so we don't want to do copy paste here. So what we're going to do is we're going to copy this map error logic. So we're going to create a
Speaker 1method that will take the result of to do on SQLX error. We'll take the static, the ID, and we'll do the work that we were doing over there. So we'll just do a result and our map error that we have up there. Now we're going to replace this. We're going to copy that. Going back to the get. And now we're going to have a method. We're going to give the result, the self table, and then the ID.
Speaker 1Press save. And everything should work great. So now that we have that, we don't want that. And we will return this. Press save and everything will work fine. So obviously we should test the update with the wrong ID as well. But for now, this is a very good start. So now to really show the power of what we have built, let's do another requirement. For example, if we wanted to capture the time where the data was modified,
Speaker 1the MID and the M time, we could go back to our SQL. We'll follow this pattern here and we're going to add MID for the modifier ID and the M time, which will be a time zone. And our design right now is going to say it's going to be new on creation, but it should be updated for each update. Now I go back to my to-do. And then let's say that for now, we don't really need to have it as part of the to-do return value, but we want to make sure that we're capturing in the database. So the only thing that we need to
Speaker 1do is as a pattern that we have done for create, we start to have the fields here. We're going to have the fields value, which we will create here, mute fields, and data fields. And now we're going to augment the fields with a CID and C time. So we can do fields, push MID, and that will be our UTX user ID. And then our fields, push C time. And
Speaker 1here in SQLB, we have row. which allows you to give a static string, which is an expression. So it's still parametrized because it's only static string, but at least you can put expressions. And here we don't forget the into, that the way the API works. Oops, like that. Now if we press save, everything should work because we haven't changed anything. But if we were going to look in the database, those two fields will be there. So now
Speaker 1for completeness, we can create our delete. method. So very simple, we have our delete with our UTX and our i64, we're going to have our SQL builder, we delete, and then we have the table name, and then the column, and then the ID obviously, then we're going to do the fetch one. And then we're going to call the same method that we had the handle fetch one result with our table and our ID, press save, everything will compile,
Speaker 1We go back to our model to do test. We're going to add our test function, our delete simple. We're going to have our fixture, same as always. We're going to have our action. Right now, we're just going to delete our to do 100. And then we're going to do this check. We're going to make sure that it's deleted and make sure that the title was to do 100. That is to check that the data return has all of the data of the deleted row. And then we can have another check, which is we're going to do
Speaker 1the list of the todo. And we're just going to use the SQLB and making sure that we have one because now we deleted the other one. We're going to press save. And then all our tests will run. We have six now and everything looks good. And the delete is here. And that's it. So that is the first part of building a to-do MVC from scratch, from the database to the web UI. In the next episode, we
Speaker 1are going to code the web layers using Warp. And then after, we are going to code the web UI. Until next one, happy coding.
Building production-ready web applications requires efficient database interaction, flexible query construction, and well-structured data access layers. We examine how these technologies work together to simplify...
In this episode, we continue our exploration of nine essential Rust programming best practices, focusing on utilities, practical examples, and software testing. Building reliable Rust applications requires more than...
In this comprehensive tutorial, we explore how to build database-driven applications using Rust and SQLite, covering essential database concepts and practical implementation techniques. We take a hands-on approach to...
Join Jeremy Chone for a live-stream session dedicated to Rust programming, software development, and practical engineering discussions. This session provides an opportunity to explore Rust development through a live...