06:00 UTC Charta Aetatis Cyberpunk

Console Newsletter Pro Sign in Early access Register
Aa · Display
Themes
Type size
Density
Hacker Culture · Lobsters · · 1:39:26 runtime

SQLite: How it works, by Richard Hipp (2024)

https://sqlite.org/talks/howitworks-20240624.pdf Comments

In the wiki SQLiteRocksDB Also namedRust
Transcript 7576 words · auto-generated captions

Machine-transcribed by YouTube. Expect errors in names, commands and version numbers.

And I'm Richard. Thank you for letting me come and talk to you today. Let's be real informal. If you have questions, raise your hand. We can go down rabbit trails. We can talk about whatever you want. I mean, I've got a huge deck of slides. Please do download them. Uh it's doubtful we'll get through all of them, but maybe we will. Who Who knows? Um and some of them have a lot of fine print. So, you may want to download them just so that you can, you know, do the expand thing and read it. Uh yeah. So, let's just get started. I'm I'm ask I I I'm the inventor of SQLite. I'm still the lead developer. There's a small team of developers that work on it. There's five committers on the project total.

And uh I I I do I I actually have a PhD,

but it's not in database technology. I've never had a course in databases. I studied computational My My dissertation is in computational linguistics. And it's way out of date because uh it was in 1992. So, uh but uh and I never I never intended to be a database guy, but here I am. So, it's a pleasure to talk to you. All right. So, what is SQLite? You I I guess you know about it a little bit. It's It's the most most widely used database engine in the world. I mean, within 2 m of you right now, there's probably about 100 different SQLite databases quietly whirling away making your life easier.

And uh how did it get that way? I Nobody's more surprised about that than me, but how did it get that way? And the big thing that I want The theme I want to give to you is that it it um

It solves more problems than it creates.

Uh there's a another person on the internet recently said um your enemy is complexity. And SQLite is a great way to reduce complexity. It's It It strives to be simple. Now, sometimes you really need complicated things. Uh there are some hard problems for which the the solution's going to be really complex, and you can't get around that. But if if if if you can simplify things and avoid the complexity, that's a better approach. All right. So, what are some of the distinctive features of SQLite? The first Most database engines are client-server. There's a separate process, or at the very least a separate thread that's running the database engine. And your application, when you link with the database library, it that's just a communication hub. You It It It It uh encapsulates the parameters, sends the message over to the database engine. The database engine computes the answer, sends the answer back to your application, and then you use it.

And that works really well, except what happens when the database engine goes down? There's a malfunction. Uh it's misconfigured. It stops working. Then your application can't work. This actually happened to me. Uh I was I was doing freelance application development, and I had an application that had to talk to an Informix database. And uh that I The The The database was controlled by a different group of people. I had no control over it, but it would sometimes go down, and then my application would say, "Hey, I can't work." And and they would send the bug reports to me because it was my application that was

popping up the error message dialog box. So, I thought What How can we fix this? And I thought, "Well, why do I even need the server? Why can't I just talk directly to the database on disk?" And I looked around, and there were no SQL database engines around that would do that sort of thing. So, I said uh I'll just write my own. And here we are 26 24 years later. Um Here's a matrix of

of uh different database engines. On the top, we've got no SQL database engines. And on the right, we have SQL database engines. And No, client-server client-server on the right. Embedded on the left. SQL below and non-SQL above. And so, there's there's use cases for all of these database engines. The most common ones you're going to see over on the on the client-server side. Those are Those are the ones that are going to be for big installations. Uh I Do you have any familiarity with Berkeley DB or RocksDB? Has anybody ever used RocksDB? Yeah, you've you've done that. Yeah. So, SQLite is kind of unique in that it is the only one where you have a full SQL database that is also embedded or serverless.

Um another distinctive feature of SQLite

is that the deliverable is a single file of C code. Usually uh when you have a library like this, you you you get a a a bundle of files or something. But And we don't It's a It's a big file. It's 9 MB right now. It keeps growing every day. We don't edit that file directly. Our source tree has a bunch of small C files. And then our build process glues them all together. But that But by delivering it as a single big file of C code, if you're programming in C or C++ or Rust, you just add this to your makefile, and suddenly you've got a full SQL database engine embedded in your application.

It's very easy to do. Uh and this makes it easier to deploy. Your enemy is complexity.

Another big feature is that SQLite has the the database is a single file on disk. It can store thousands of different tables, views, triggers. It's very space space efficient. But because it's a single file, you can treat it as as kind of an application file format. If you're building an application and you need to store some data, you can make SQLite an SQLite database your your file format. You've got the full power of SQL, transactions, and uh

uh the query language, but you can store it in a single file. And then when you when you're when you created that file, you can send it to your friends by an email attachment or something like that. People say, "Well, yeah, but you know, I I I want to use text for my application file format because I I don't want to depend on some opaque binary file. You know, I I want to be able to read it. I want it to be able to last." And well, it turns out that SQL Yeah, the the SQLite database is a binary file, but it's an open format. It's been stable since 2004. It has Well,

we've added enhancements, but it's backwards compatible to 2004. Uh the complete specification is online. It's readable and accessible. It's about 20 pages, depending on your font size. It's completely cross-platform. Um it's recommended by the US Library of Congress as

a file format for the long-term storage of archival data. And we're promising to support it through the year 2050. So, don't worry so much about that. Other people come to me and they say, "Look, um I'd like to use a database, but I need my application to be really fast. I need very fast access to my application. I can't have a date an SQL database engine in between me and my data. It will slow things down too much." Turns out you can actually get data out of an ask out of an SQLite database faster than you can read individual files on disk. This is a study we did for a cell phone manufacturer, where they wanted they have a bunch of of thumbnail images, and they needed to be able to pull them off very quickly. And they wanted to know, "Do we store them as blobs in an SQL database using SQLite, or do we store them as individual files on disk?"

And it turns out that you can read these blobs faster or that you can read the thumbnails faster if they're stored in the database than as individual files on disk. And you're thinking, "Whoa, how is that even possible? Because the database is a file on disk. How can you be reading it faster?" Well, here's the thing. If you've got a bunch of files on disk, to read a bunch of them, for each one, you have to call open, read, and close.

If you're reading them out of the database, you open the database file just once. You only call open and close one time, and then you do lots of reads. And it turns out the overhead of running SQLite to access these blobs is less than the overhead of calling open and close. So, it's going to be fast enough for you. Well, but But you're worried Well, what about licensing stuff? I don't want third-party code in my thing cuz I you know, I don't want to the hassles of keeping track of licensing. We have released all of the SQLite source code into the public domain. And there's a lot of paperwork we had to pull that off.

Um but it did. And that's one of the reasons we have such a small development community. Uh With a lot of open source projects, people can contribute freely. And you can do a pull request. And we don't take pull requests. And the reason for that is or one of the reasons is that if if somebody sends us some code, and we incorporate it into SQLite, then they own the copyright on that code. It's by default. And And And unless we go through this elaborate legal process for them to release that that copyright, that would contaminate the project. So, we're very uh very strict about who can contribute to the code.

Uh but that means you don't have to worry about licensing problems and and

and and possible legal repercussions. Now, yeah, it does say SQLite, and people are turned off by that and think, "I don't need a light database. I need a real database, not a toy database." The light in the name um is there because I'm notoriously bad at naming software projects. Okay, don't don't too much too much weight on that. It It's Okay, it's not a big data data database, but it will do a lot of stuff. You can have a one writer and any number of concurrent readers all at once. And I say one writer, it's you can have multiple processes writing, that's not a problem. It's just they have to take turns.

And the library will will will queue up your requests for you. But just know that only one at a time is going to be going. You can have gigabyte size strings and blobs. Uh the databases can be up to 281 terabytes in size. Now, they do have to fit in one file. Uh good luck finding a laptop where you can store a single 281 terabyte file.

Okay, that's that's going to be hard. 64-way joins, 200 columns per table and indexes. There's just no arbitrary limit on the number of columns and indices.

So, you're thinking about well, hey, I need a database engine for my project. What database engine should I use? Here's a checklist. You ask Is Is my data remote from the application? By remote, I mean is it on a different machine? Do you have to go across a network to get to the data? You should probably choose a client-server database in that case. And the reason is is the database engine acts as a filter to the data. A lot more information flows from the

disk drive or the SSD to the database engine than flows from the database engine to your application. And so, if if information's going to have to cross a network, you want the low bandwidth chunk to be over the network. And that means that you want the database engine to be on the same machine the same physical machine as the data. And so, that's a good reason. Now, SQLite will work across a network file system. Uh but performance isn't great on a network file system. It really wants the the file system to be local. Uh you know, another thing is that a lot of file systems have um a lot of network file systems have bugs in their locking protocol.

It's gotten better in recent years. It used to be really bad. Um but and if there if you hit a file system bug, it it with locking, it could possibly corrupt the database. I Do you have big data? And I define big data is any data that's larger than 281 terabytes. So, uh and and do you have Do you really need concurrent writers? A lot of people think they need concurrent writers, but when you really get right down to it on if you've got a single disk drive or single SSD, there's one wire that goes between the CPU and the storage device. You're not really writing multiple or concurrently. It's still being queued up. Do you really need it?

Sometimes you do. Uh but if you need any of these things, go with client-server. If you If If none of If you don't answer yes to any of those questions, SQLite is a much better choice. Where people mess this decision up is that they will say, "Okay, I don't need any of this stuff. I'm just going to write it directly to the disk. I'm going to I'm going to write a big XML file or or take a bunch of JSON and I'm going to put it in a file that's going to make my database." And you know, when you do that, you can do that if you want to, but you're going to lose all of the transactional capabilities. You're going to lose the query language. You're going to lose the file format that's guaranteed to work through the year 2050.

It's just um harder to work with. You're going to make your life more difficult unnecessarily. You're going to increase complexity in your application. And complexity is your enemy. So, uh I I wrote SQLite and put it out there and I thought that it'll be like all the other open source projects I've I've started and it'll get 10 downloads per year or something like that. But to my amazement, it went viral. It started going into cell phones. I I wrote it in 2000 initially and uh the smartphones really didn't come on the scene until around 2006. So, this was all starting about then. And so, these days SQLite is found in all of your devices. It's in every phone, your Mac and your Windows machine. They require They come with SQLite built in and they require it in order to boot. They will not boot without it.

It's in all your browsers, all your bookmarks are stored in SQLite databases. Uh it's in It's in your car, probably. It's in all kinds of appliances. It's in the avionics of the Airbus A350. It's in various spacecraft. It's used in everything. Uh We It's hard to measure how many uses there are. I think we're pretty sure that there's probably a trillion active databases right now. Um we There It's It's probably there are more very likely there are more SQLite databases running than all other database engines combined. Some people say that SQLite might be the most widely used bit of software in the world today. My personal opinion, I think that the LZ compression library might be a little bit more, but um it's it's certainly within the top 10.

So, so that is a kind of a summary of what SQLite is. I wanted to talk to you today about how it's actually implemented. And why do you care? Well, it is a widely used product and you're all experts in databases or will be. And so, even if you don't use it yourself, you kind of need to understand how it works on the inside. Not that it Maybe you want to Maybe you want to make your own fork of it and and and do something

and make it better or something. In which case you kind of need to kind of need to understand the internals. But even if you don't want to do that, even if you're just using it in an application, if you understand what's going on behind the curtain, you'll be able to use it more effectively. Also, the the structure of SQLite, though very different from other SQL database engines, there are common themes that run through them all. And if you understand how SQLite works, then when you go to study another database design, it'll be a much more familiar to you. So,

the application programming interface. This is This is not real code. This is pseudo code uh because I've left a lot out for clarity's sake. But this is a looks kind of like a C program and its job is It takes two arguments. The first argument is the name of a database. The second argument is an SQL statement of some kind. And what this program does is it opens the database, runs that one SQL statement. If the SQL statement's a query, it prints out the results and then it exits. So, let's talk about how this works because understanding the interface is key to understanding how the thing is put together. So, there's two objects you need to pay attention to. There's the SQLite3 object declared first. It's a a database connection. And then there's the SQLite3_stmt or statement object. That represents a single statement of SQL.

We start out by calling SQLite3_open, giving it the name of the database file. And you get back a connection. Skip down to the bottom and you can see where we actually close that connection. That's the destructor for the database connection. The next statement is SQLite3_prepare.

Given a database connection and the SQL text to be run, we're

creating what's called a prepared statement, which is the SQLite3_stmt object.

And then the next lines of code are going to run that object. The next The next line of code is column count. It's just getting the number of columns in the result set. If it's an insert statement or an update statement that doesn't return anything, that might be zero. But it's you If it's a query that returns five columns, then it'll be five. Then we go into a loop. We call SQLite3_step. This begins executing the SQL. And it executes up until the point that it either finishes or it finds one row of result. If it finds a row of result, it returns SQLite3_row or No, just SQL light row.

And then inside the loop, we're going to print out the value of that row. Um I've got a couple of APIs here, SQLite3_column_name and column_text. So, and it's looping through the columns and it's printing out the name of the column and the value of that column as text. And then after it does that that one row, it'll call SQLite3_step again and it will advance to the next row and do the same thing. And so forth. And when it finishes, it will return SQLite3_done. And then it returns Finalize is the finalizer for the prepared statement and then we close the connection and we're finished. That's the basic idea. Um I've left out lots of error handling here. If you're you know, what happens if you give it invalid SQL? You're going to get an error. What happens if you hit an error while you're running? You're going to get an error. I've left out those details. They're They're unimportant.

The point is kind of this. Uh you can think of SQLite as a compiler

for SQL statements. Think of each statement in SQL as a miniature program. And there are two parts of SQLite. There's the compiler that takes the program and compiles it into executable form. And then there's the machine that executes the result. So, really in SQLite, the prepared statement is just byte code that's going to implement what you've asked to do via SQL. Now, when we're working on SQL I, we the developers, we kind of break it up into these six components. Parser, code generator, virtual machine, B-tree, and pager. So, let's go over them one by one. The parser, this is what takes the SQL text, analyzes it, uh

generates an abstract syntax tree. Does everybody Is it Who's had compiler construction? Who knows what parsing and an abstract If you If you know what an abstract syntax tree is, raise your hand. Okay, that's great. I love it when people know this and I don't need to talk about it anymore. So, the parser does that part. You get an abstract syntax tree. That goes down to the code generator, and this is where all the what I think is the most fun and amazing magic happens. It has to take this abstract syntax tree and convert it into bytecode. Does all the analysis, the error checking, and that sort of thing.

Um so, really, if you think about it, the first two modules here are the compiler. And the last four modules are the part that run the program.

Let's keep going. The virtual machine, it's a very simple virtual machine. I say bytecode, people You've probably heard of Java bytecode. Maybe you've heard of um there's other bytecodes out there. Uh P-code, there's there's a bazillion of them. The bytecode in SQL I Actually, here's an example. Is a little different. It Every instruction has an op code and five operands. It's a three-address machine. The And it it the instruction format is fixed like that because that way we can print it out as a table. But you Oh, I should I should mention that if you want to see the bytecode for any SQL statement in SQL I, you just pre-pend the keyword explain in front of the statement and run it, and it will print the bytecode.

The um And we'll talk about this in detail coming up. The It's a little The bytecode is a little bit different in that uh with most bytecode, you have things like load the value of load some value into a register, add two registers together, move move the move the results somewhere. And SQL I bytecode has that stuff, but it also has some very high-level things like create a new B-tree, create a cursor into this B-tree, seek that cursor to a particular point in the B-tree, and that sort of thing. Things that are very database specific. We will go into some details on that in a minute. Let me just point out quickly that in this printout of the bytecode, the stuff shown in gray is only there for debugging. It's only in debugging builds.

Uh when you're when you when you're in production, uh it those those details are left out. Um also, I mean, it doesn't actually store the name of the op code. That's decoded for you for display purposes. And the indentation here that's showing the loop, that's added also. We'll talk more about that later. Now, if you want to play around with SQL I, here are instructions on how to build a debugging version, and you can study this later. The advantages of having a debugging version are that when you're typing in interactively SQL, you can type dot tree trace minus one, and that turns on lots of debugging stuff that, for example, prints out the abstract syntax tree as ASCII art, so that you can kind of see what's going on. And as it's transformed during the compilation process, it'll print it each step along the way.

And things like EQP, which stands for explain query plan, EQP trace

traces the execution of the virtual machine. So, as the bytecode is running, it shows each instruction and the registers that it's using and changing as it goes along. So, that's the virtual machine. The bottom three layers could be grouped together and be called the storage engine. And it's it's a B-tree based storage engine. Do you remember that other slide I showed you where we had these databases that were serverless and non-SQL, things like RocksDB and BerkeleyDB? The bottom three pieces of SQL I are really kind of one of those. And in fact, if you wanted to, you could go into the SQL I code and kind of chop off those bottom three pieces and plug in some other storage engine that you wanted to do. And this has been done multiple times.

Oracle once had a product called the uh BDB SQL I for they took the bottom three

layers off and they stuck on BerkeleyDB, which they bought from Sleepycat, and that was their product. Uh one really famous example of this happening is the database engine called CalmDB 2. Uh this is open source. It's developed at Bloomberg. Bloomberg is a fintech in New York City, founded by Michael Bloomberg, former mayor of New York, and it's a big thing in the finance industry. And they have a uh uh uh a storage engine that is amazing. It It runs in multiple data centers, highly redundant. You can An entire data center can go offline in the middle of a query, and somehow it still manages to finish the query.

Uh And anyway, they they've got a a team of engineers that work on this all the time, but they don't want to mess with SQL. And so, what they do is they just pull the SQL part of SQL I out and stick it

on, and that becomes CalmDB 2. So, anytime you're doing high finance, you're using SQL I apparently. So, the storage engine summary in SQL I, it is a row store. There are variable-length entries, and it's a forest of B-trees. We don't uh I mean, a lot of SQL database engines, the the row content is stored as a heap or some other structure. Everything in SQL I is a B-tree. We don't have any kind of storage other than that. Let's go on down to the B-tree layer. Uh this is just a B-tree implementation. We have two different types of B-trees, uh classic B-trees and B+ trees. You know, there's a bazillion types of B-trees. Have you Have you Have you studied this and seen them all and trying to keep track of them all? And they all have names, and the names are not reflective of how they actually work. And so, I Whenever I'm talking about B-trees, I have to go pull a book out and say, "No, no, which name was to which I I get confused."

Um but we're using B-trees and B+ trees

with variable-length entries, variable number of entries per page.

The pager layer is what's responsible for providing atomic uh commit and rollback. Uh it's it's it's it's responsible for keeping things ACID. The pager does not know anything about what's An An SQL I database is organized as an array of pages. And their numbers started numbered starting with one. The first page is one. There is no page zero. Zero means like the null pointer.

And the pages are all the same size, and that size is going to be a power of two between 512 and 65,536. And the page number is a 32-bit unsigned integer. So, if you take two to the 32nd power and multiply by the largest page size, 65,536, you get 281 terabytes. That's

the final size limit. Now, if you're using a 4K page So, the the page size Every database can have has has a fixed page size. It doesn't matter what it is. By de- It defaults to 4K because that seems to match hardware the best. If you go with a 4K page size and multiply that by two to the 32nd power, then you're going you're limit only you're limited to a 17 and 1/2 terabyte database. That's still more that's going to fit on your laptop, so you're probably still okay. That's That's for small data. That's right, 4K. So, um the the the pager is also responsible for concurrency control and to provide cache to the B-tree. The B-tree is only dealing with pages that are already loaded into memory.

Uh then the bottom layer is the OS interface, and this is what makes SQL I portable. This is just sort of a it's an object that that provides a common way of talking to the underlying operating systems. There are currently two operating systems supported, Unix, which includes Mac and Android, and also Windows. We used to support OS 2,

but we couldn't find anybody who still used OS 2, so we dropped that. Uh I hope that we never have to add another one, but but because Unix is sufficient for everyone, I think. Um the that OS interface is really an object, and it's runtime pluggable. You can You can write a new one yourself that or You can write a little module yourself, which we call a shim, that has the same interface, that would do something like encrypt the data before it goes to disk, or compress the data before it goes to disk, or maybe you're debugging and you just want to log what's happening.

We use and and you insert this shim in between the real OS interface and the and the rest of the system, and it continues to work normally. We use this for testing, for fault injection. How do you test a database engine uh to make sure that it recovers correctly from a system crash? How do you do that? Do you sit there and start something going and then I'm pull the power plug? I mean, that does happen. There are companies that do that sort of thing, but we want to test that we can actually run and we don't have to reboot our machine. So, like we have shims that we insert that causes the database file to be damaged in ways that would be typical of the damage you would get if you took an unexpected power loss.

And then we're able to see do we recover from this and does the the transaction either fully commit or does it roll back? So, it's very useful for that. So, oh, I forgot to mention I understand you guys get a break somewhere in the middle of this.

When you've heard enough and you need a break, just call out to me. Okay? And you know, I I didn't mention too. Look, if if I say something coming up we're getting into some more detail there. If I say something coming up and and and you want to push back, feel free to do that. You're not going to hurt my feelings. That's not a challenge, but at the same time don't worry about it. Uh if if if you think that this is a if I've done something if you if you know a better way to do something, speak up. We'll talk about it. Actually, I just have a question. Sure.

Have you ever considered bypassing the file system and directly going to the block device? The question is have I considered bypassing the file system and going directly to the device? We actually have a a sub code in the source tree that does that. This is a I'm going to take time here to tell you this is a crazy crazy story. The um

In the United States, we have this thing called a muscle car. Do you all know what a muscle car is? You know, and and all the cars now they have this little thing under the dash that you plug in that you tune the engine. And you used to be go to performance car stores and they had a little thing that would plug into that. And it go buy a Dodge Charger and you could plug this thing in and push a button and it would give it an extra 20 horsepower. But then you know, before you take it into the dealership for service, you need to plug it in again and set it back to the way it was lest you void your warranty. So, anyway, this this company approached us and and this the the little CPU on that thing, they didn't want to pay the licensing fee for the file system that went with it.

But all their data was in SQLite and so they asked us to write a a a um

uh an OS interface that talked directly to the SSD. And we have a prototype of that that's in the in the source tree so you can do that. I I I I don't recommend that, but you can do that if you want to. Uh so, more details. Let's go back up the layer a little bit. All right. How do you do power How do you do a layer You're you're making changes to hun- dozens, hundreds, thousands of pages in this file. How do you write them atomically? How do you write them such that if you lose power in the middle, either they're all going to get written or none of the none of them are going to get written.

That's a tricky problem. I'm going to show you how that works. We've got two in in the file system, you got the actual data on disk and of course, I'm using I'm old school. I call it disk even though it's now always an SSD, right? We understand that. When I say disk, I mean your mass storage device. You've got the disk where things are persistent and they persist across power failures. And then you have a cache of the disk that's inside the operating system, the OS cache. And then you have the information in user space. So, when you first boot up, everything's on disk and the OS cache is empty.

And you want to read something out of your database. There could be multiple processes that want to read out of the database. So, we don't want somebody reading and writing at the same time and overriding us. So, we take what's called a shared lock on the database file and that prevents somebody from writing stuff out from under us. Uh you know, I I I skipped a slide back there. I'm I apologize. I'm going to back up a little bit. There are two ways that SQLite does this. There's rollback journals and write-ahead logs. Rollback journals are the default because they work even on network file systems.

That's what I'm showing you now, rollback journals. I'm going to show you a second way which is has more concurrency and is faster called write-ahead log. It's not the default. You can turn it on easily. It's not the default because it requires a small amount of shared memory. And so, if you're accessing a database file across a network file system and you're accessing it from two or more computers, those they can't share memory because they don't there's there's no memory to share. And so, it won't work in that environment. And so, that's why it's not the default, but it is faster and it's recommended in every case where you can use it. But we're going to go over rollback journaling first. So, you do a read, you want to read three pages out of the out of the database and it when you do the read call, it pulls that stuff into the operating system's cache and then you pull it into user space and you can do stuff with it.

So, then okay, so now I want to write to this. I want to make a change to the database. Uh the first thing you do is take a reserved lock which tells everybody else, "Hey, I'm getting to ready to write. I don't want anybody else to

try and write right now. Just give me a second. I'll be just a second." And then after it takes the reserved lock, it hasn't changed anything yet. It makes a copy of the original content of the pages you're going to change in a separate file called the rollback journal. And it's the name of your database file with {dash} journal at the end. And That's copying pages of It's copying the It's copying the complete content of the original page because the pager does not know anything about the internal structure of the B-trees. So, yeah, I know yeah, you could you could you be faster if you copied only the parts of the page that changed?

Maybe, but that would make things more complicated. That's good for like copy on write protection or something. Yeah, and but and and right. And so, this is a simpler way, but it's fast enough and it um complexity is your enemy. So, we're going to keep it simple. It copies the entire page. Now, it's still in cache. It hasn't made it to disk yet. So, if you lose power now, all this is going away. But you can go ahead and make changes to the pages in memory. And I've shown that by these pages being colored orange or tan or brown or something. Now, at this point at some point you've got to call fsync or in Windows it's called

flush file buffers flush file buffers. Is that the name of the API call? Does anybody remember? I don't remember. I wrote this 25 years ago. I don't remember what it's called. It has worked fine ever since. But there's a call that that causes all of the operating system cache to be flushed to disk and and it returns after everything is safely in persistent storage. And at that point, we can take an exclusive lock and then we can write our changes to the file itself. And when we do the write system calls, it only goes into the OS cache. We also have to do another fsync to push it out to disk and make sure it's safely on disk.

And then and only then, we delete the rollback journal. And and the deletion of the rollback journal is an atomic operation and this is what causes your transaction to commit. If at any point prior to this, the um if at any point prior to deleting the rollback journal, if you lost power, when you booted back up, you might have say incomplete changes in your disk file. But you'd also still have a journal file sitting right there beside it. And so, when SQLite would start up, it would get take its shared lock and then immediately notice that you have that journal file sitting there. We call that a hot journal.

We've got to deal with that. And so, the first thing it does as soon as it's starting up when you call SQLite 3 open, is it takes an exclusive lock, it reads the journal file and copies it onto the disk restoring the disk to the state it was before you started your transaction. It rolls it back and then it deletes the uh deletes the um journal and goes about its business. So, is the existence of the journal file signaling that something went wrong with this transaction before? Yes, so the existence of the journal file signals that something went wrong. Got a question in the back. I was wondering if the locks are somewhere shared memory or also in the file because if the computer crashes, then locks would they still be there or would they change?

No, locks are are are not persistent. They are in they're in the operating system memory. They're in kernel space. So, if you lose power, the locks vanish. And you're using uh that the kind of locks not to be shared. I I'm not I'm not hearing what you're saying. Say again, please. Are you using the lock feature of the operating system? Yes. Okay. We're using We're using file locks on the operating system. Which, you know, for historic for history buffs, this is really tricky to do on Windows 95, which was the predominant operating system when I wrote this. So, I thought that uh operating system locks aren't really easy to use on Windows either.

Yeah, Linux has its own set of problems with with file system locks in that if you if you have a if you have a lock on a file if you if you have two threads and both threads open the same file with different file descriptors, and this guy over here sets a lock on the file, and this guy just closes the file descriptor, it deletes this guy's locks. It's insane. You can tell which parts of Unix and POSIX were developed by uh you know the the boys at Bell Labs and and which got which parts were developed by some committee at at at somewhere, you know. And this is one of those committee parts.

Yeah, it it's insane. And there are extensions like uh it was a big deal a few years back when Linux added uh they call it um but there's a name for it, but they have a a better type of locking where closing one file descriptor does not delete the locks on the other file descriptor. And the name escapes me right this moment. It's not intuitive. What was called? No, no, it's not mandatory locking. That's something very different. Um I'll I'll think of it I'll think of it later. I haven't had lunch. After lunch I'll I'll immediately pop to my head. But um and and we're we're kind of watching this closely and Mac has added this too with an incompatible interface.

So, we're kind of watching this closely and at some point we might start using these locks. Right now with there's a lot of logic inside the OS Unix.c file

to deal with that problem. And we do deal with it, but you have to be very careful with that. Okay, so um the preferred form of doing things if you can do it is the write-ahead log file. This is much faster um and it gives you more concurrency. And this works as before. You've just got a uh a shared lock on the on the cache. You read it in the user space. Now when you get ready to write, you can just change space you can just change content directly. You don't need to create a copy of the original content. Just go ahead and make the changes to the pages you have in your private space.

But before you write it back to the file, um you write your changes into a separate file called the write-ahead log or wall. And you'll notice that the last one has a little dot in the middle. That means that's uh the end of our transaction. There's a special little mark on there that's that means end of transaction. And and and we haven't had to do an exclusive lock on the database. That means other people can be reading this while we're writing. That's very important. So, and then so some other process comes along and they want to write, too. They could pull in a different set of pages and now when they're pulling these pages in though, they have to know that the wall file exists.

Because if one of the pages they wanted to pull it it looked like page number two had been previously modified. And so rather than to pull the original copy, it's going to pull the modified copy that's in the wall file. Well, how does it how does it how does it know that it's there? That was that shared memory part I was talking about. When whenever you're using the wall mode, every process that opens the database that allocates a small amount of shared memory, which is a hash table, which tells it which pages are in the wall file and where they're located. So, it loads in you know, so a second process can read this stuff uh out of the wall file

and and do its own thing while these things are being written. And the second process might make its own set of changes and they'll get appended to the wall file like this.

Now eventually and if you if this ran if this kept going, eventually the wall file would grow without bound and it would be much bigger than the database and that would not be a good thing. So, every now and then

Related videos

Discussion
0 comments 0 from AI Characters · 0 readers

Sign in to join the discussion.

Make the first comment.

That's Cyber for today

Tomorrow's desk, in your inbox by 06:00 UTC. The week's best stories, every Sunday. The month that mattered, on the 1st.

Drawn from the 537 sources the paper read this month. Text and HTML, one-click unsubscribe, free.

How often
Your desks