10 ms·
Strict Tables – Column type constraints in SQLite - Draft
- goodells 5y agoI had no idea SQLite was so fluid with its column types - that's kind of alarming. I guess it's fine if you still have an ORM in between you and it, and this STRICT syntax is probably the most reasonable workaround, but it just seems like a band-aid on top of not following the sensible pattern of every other database engine.
- rastapasta42 5y agoI find in practice this limitation is not an issue and column flexibility does not get in the way.
- temp8964 5y agoThe problem is not it does not get in the way. The problem is that some expect it to get in the way when the data is not right and assume it will do when in fact it won’t .
- chousuke 5y agoThat's kind of the problem. The database absolutely should get in your way if you try to put nonsense data in it. For the kinds of uses SQLite sees, the loose approach to data integrity may not have caused much grief, but I can't imagine many situations where it would have helped either. Having support for enabling sane behaviour is welcome even if it has to be opt-in for compatibility.
- kevin_thibedeau 5y agoIt's designed to integrate with Tcl with minimal fuss over typing. The world latched on to it because of its dependability and relative light weight.
- JNRowe 5y agoI wouldn't go as far as to say I'm aghast at the lax typing¹, but I look forward to this change hitting a release. Adding some sugary support for a strict DATETIME type in a future release would tick every box I want from sqlite. In a couple of projects I work on the main reason for plopping an ORM between sqlite and the application is to implement type strictness, and removing that need would be excellent. It would also neatly shut down a discussion that comes up far too often when someone wants to use sqlite as data store, which is surely a good thing as it is often just a stop motion argument in my experience. ¹ I am closer to that camp iff I have to choose an option from the article.
- gwd 5y agoI think "other developers are aghast" is a bit strong for technical documentation. I was certainly never aghast: knowing that SQLite started its life aimed at TCL, the decision made sense, and the commitment to backwards compatibility is admirable. Nonetheless I certainly welcome this change. The "doesn't enforce foreign key constraints by default" is much more surprising / annoying to me.
- JNRowe 5y agoI suspect if I had to answer as many questions/rants about type strictness as the authors do I'd probably choose much stronger language. It definitely wasn't intended, but I guess my earlier comment could be read as the ten-thousandth entitled complaint of the day too.
- SQLite 5y agoScan this HN thread to see comments from devs who are aghast. :-)
- crazygringo 5y agoAnd even more, scan the HN thread from 16 days ago: https://news.ycombinator.com/item?id=28050198 https://news.ycombinator.com/item?id=28050198 "Aghast" feels like an appropriately accurate characterization to me. ;) I'm actually curious if this change was a direct (and incredibly fast) reaction to that thread, or if the timing was just coincidental?
- ysleepy 5y agoNice to see. I almost never want mixed values in a column, so being able to turn on a strict mode preventing inserting a string into an int column is very welcome. Also the per-table opt-in is reasonable. sqlite is really becoming this bedrock thing in the computing landscape, it's silently everywhere and all agree that it is kind of a good thing.
- justinclift 5y agoThis is really welcome. One idea for an approach I had a while back (but haven't attempted writing code yet) was to see if "personalities" could be implemented. For example a "PostgreSQL" personality (set via PRAGMA maybe?) which dynamically imposes the same type names and "limitations" on SQLite as PostgreSQL. Ditto for other SQL dialects (MySQL, etc). SQLite already has the flexibility to allow the data types, so this idea is a way of putting constraints in place that are really beneficial for a _lot_ of common use cases. eg "You're using SQLite as a local test for a [PostgreSQL/MySQL/etc] prod database"
- electrum 5y agoThe H2 embedded database has compatibility modes for other databases, which seems helpful for testing, but ends up being incompatible in various ways for anything non-trivial. You end up fighting the compatibility and skipping useful native features of the target database, while still not having confidence that the code works on the target database. We now use the awesome Testcontainers library (available for multiple languages) that makes it easy to launch the real database in a Docker container. Testing applications against multiple databases is now trivial.
- justinclift 5y agoThanks, that's interesting and a really useful data point. :)
- zarzavat 5y agoHonestly in that case you should just use Postgres locally. SQLite was never meant to be a stand-in for a true RDBMS. As they say, it's intended to be a replacement for fopen(). The fact that it works for local development is a fluke.
- nicoburns 5y agoYeah, I've never understood people's aversion to running Postgres or MySQL locally. They're super easy to install, and they'll run in the background using minimal resources ready for you when you need them.
- spicybright 5y agoHuh, thought columns already had strict datatypes. Only used postgres before. Very scary sqlite doesn't do that already...
- simonw 5y agoI'm so happy to see this. Personally I don't particularly care - SQLite's loose typing has never caused any problems for me - but I've seen SO many programmers dismiss SQLite as an option because they find its loose typing distasteful. Eliminating one of the most common reasons that people reject SQLite feels like a big win to me.
- pmontra 5y agoI inherited a PHP/SQLite project years ago. I found timestamps with three different formats in a column because different PHP pages had different ideas of what a timestamp is. OK, the problem was the original developer that wrote all of that code but the database made it too easy to write that horror. I wish they add a real strict type for dates and times too.
- simonw 5y agoOuch, that sounds nasty! There's a pattern for enforcing datetime formats using a CHECK constraint which I've not tried myself yet but which looks like it could work: https://sqlite.org/forum/forumpost/4f4c96938f4bef32?t=h https://sqlite.org/forum/forumpost/4f4c96938f4bef32?t=h
- Cyberdog 5y agoThat's hardly unique to SQLite. I'm a huge fanboy of SQLite, though I have to use MySQL in pretty much all of my client work since I more often get hired to work on existing projects than start new ones. There's three common ways to store timestamps in MySQL and they all stink; - Use an integer column with a Unix timestamp. Not human-readable and no sub-second accuracy if you need it (unless you store the time in milliseconds instead of full seconds, requiring larger int columns, or just get completely crazy and use a float field of some sort. - Use a `datetime` field. Human-readable, supports milliseconds natively, and supports any time between years 1000 and 10,000, but doesn't store a time zone - so if you define the column with something like `'created' TIMESTAMP NOT NULL DEFAULT current_timestamp`, who knows what will actually be inserted in that field when the row is created? - Use a `timestamp` field. Like datetime fields, you get a human-readable field with sub-second precision, but the range is only from the Unix epoch to Y2K38, which is seventeen years away now. These fields store the date unambiguously as UTC - hooray! But… when you retrieve the date, the time will be adjusted "back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server's time. The time zone can be set on a per-connection basis." You can make an unwieldy cast to get the date as UTC - `SELECT CONVERT_TZ(created, @@session.time_zone, "+00:00") AS created_utc` - but obviously this is easy to forget about and performs an unperformant double-cast. All three of these options suck in their own distinct ways. All this rant is to say that date storage in at least two of the most common databases is a bit of a mess right now (it's been long enough since I've used Postgres that I can't recall if things are any better there, but I'm sure one of its fanboys will let us know soon enough if it is). So don't get too hard on your previous developer or blame SQLite in particular.
- scottlamb 5y agoAwesome. The weird column type behavior is possibly the only thing I dislike about SQLite3. Having to add the word "strict" at the end of each "create table" statement is a slightly annoying thing I might forget, but it's a reasonable concession to compatibility, and I can write a schema test to catch omissions.
- epilys 5y agoInteresting that values are still coerced if possible. I'd expect STRICT to be absolute in this case.
- temp8964 5y agoI am not surprised that many comments show surprised about the column types are flexible by default. I guess most people don’t read the original documentation before starting using it. This happens because most tutorials do not mention this either. I will not be surprised if most authors of the tutorials don’t know this either. I did read some webpages on the official website, but I don’t remember seeing this either. It’s possible that I read pass this information but did not pay attention to it.
- simonw 5y agoThis STRICT feature is a brand new (currently marked as DRAFT) and hopefully scheduled for the next release of SQLite. I believe this document only showed up on the website today.
- em500 5y agoSQLite's flexible datatype approach is mentioned in "Distinctive Features Of SQLite"[1], "Quirks, Caveats, and Gotchas In SQLite"[2] and detailed in "Datatypes In SQLite"[3]. I find it surprising that apparently many devs use SQLite without knowing any of this. Pretty much the first thing I try to find out about languages or databases new to me that I might want use is the datatype support. [1] https://www.sqlite.org/draft/different.html https://www.sqlite.org/draft/different.html [2] https://www.sqlite.org/draft/quirks.html https://www.sqlite.org/draft/quirks.html [3] https://www.sqlite.org/draft/datatype3.html https://www.sqlite.org/draft/datatype3.html
- sradman 5y agoGreat news, domain constraint enforcement is a welcome new feature. However, let's not throw the baby out with the bathwater; being able to specify an ANYTYPE/VARIANT column on a STRICT table would make this feature more useful. The canonical use case for ANYTYPE is a BIGTABLE or Entity–Attribute–Value (EAV) model. I haven't checked recently, but I was unable to determine the type of ? parameters in SQLite prepared statements. Maybe this is something that can also be accommodated with STRICT tables.
- SQLite 5y agoIn something like this: CREATE TABLE t1(a INT, b TEXT); INSERT INTO t1(a,b) VALUES(1,'2'); SELECT * FROM t1 WHERE a=?; The type of the ? is ambiguous. You can say that it "prefers" an integer, but most RDBMSes will also accept a string literal in place of the ?: SELECT * FROM t1 WHERE a='1'; -- works in PG, MySQL, SQLServer, and Oracle
- sradman 5y agoI'm interested in the API interface while the string literal example is more about the SQL language. JDBC has long provided prepared statement metadata that is used extensively by numerous tools.
- aidanhs 5y agoI've created ~five new projects over the past year using SQLite and I've got into the habit of creating tables like this: CREATE TABLE tIssue ( id INTEGER PRIMARY KEY NOT NULL CHECK (typeof(id) = 'integer'), col1 BLOB NOT NULL CHECK (typeof(col1) = 'blob'), col2 TEXT CHECK (typeof(col2) = 'text' OR col2 IS NULL) ); This has saved me from a lot of errors and has been useful, but it's just so easy to let things drift, e.g. removing `NOT NULL` constraint and forgetting to also update the check constraints. I'm also horrified at the auto-conversions that I've just learned about from this link that I'm not protected from. I'm very much looking forward to using strict tables.
- em500 5y ago> I'm also horrified at the auto-conversions that I've just learned about from this link that I'm not protected from. Most of the common databases that I'm aware of (PostgreSQL, MySQL, SQL Server) do implicit type conversion on insertion (as well as in in many other places). I haven't checked this, but it wouldn't surprise me if that's actually ANSI SQL standard behavior.
- derefr 5y agoANSI SQL provides “CREATE CAST […] AS ASSIGNMENT”, which will define a cast that gets used implicitly to get from type X to type Y when you have a tuple-field (e.g. table-row column, composite-value member field, stored-proc parameter) of type Y, and an expression-value being passed into it of type X. Quoting Postgres docs (because ain’t nobody paying for the ANSI SQL standard just to quote it): > If the cast is marked AS ASSIGNMENT then it can be invoked implicitly when assigning a value to a column of the target data type. For example, supposing that foo.f1 is a column of type text, then: INSERT INTO foo (f1) VALUES (42); > will be allowed if the cast from type integer to type text is marked AS ASSIGNMENT, otherwise not. (We generally use the term assignment cast to describe this kind of cast.) Presumably, in any ANSI SQL-compliant DBMS, you could redefine whatever assignment casts are annoying you to be non-assignment casts. (AFAIK, there’s no ANSI SQL standardization on what casts must be assignment casts; so lowest-common-denominator SQL-standard-compliant queries shouldn’t be relying on the presence of any defined assignment casts.)
- simonw 5y agoIt looks like this check-in from yesterday contains the implementation and tests: https://sqlite.org/src/info/f9c1d3441b87ee29 https://sqlite.org/src/info/f9c1d3441b87ee29 As always the TCL tests are worth admiring: # STRICT tables have on a limited number of allowed datatypes. # do_catchsql_test strict1-1.1 { CREATE TABLE t1(a) STRICT; } {1 {unknown datatype for t1.a: ""}} do_catchsql_test strict1-1.2 { CREATE TABLE t1(a PRIMARY KEY) STRICT, WITHOUT ROWID; } {1 {unknown datatype for t1.a: ""}} do_catchsql_test strict1-1.3 { CREATE TABLE t1(a PRIMARY KEY) WITHOUT ROWID, STRICT; } {1 {unknown datatype for t1.a: ""}} do_catchsql_test strict1-1.4 { CREATE TABLE t1(a BANJO PRIMARY KEY) WITHOUT ROWID, STRICT; } {1 {unknown datatype for t1.a: "BANJO"}} do_catchsql_test strict1-1.5 { CREATE TABLE t1(a TEXT PRIMARY KEY, b INT, c INTEGER, d REAL, e BLOB, f DATE) strict; } {1 {unknown datatype for t1.f: "DATE"}} do_catchsql_test strict1-1.6 { CREATE TABLE t1(a TEXT PRIMARY KEY, b INT, c INTEGER, d REAL, e BLOB, f TEXT(50)) WITHOUT ROWID, STRICT; } {1 {unknown datatype for t1.f: "TEXT(50)"}} do_execsql_test strict1-2.0 { CREATE TABLE t1( a INT, b INTEGER, c BLOB, d TEXT, e REAL ) STRICT; } {} do_catchsql_test strict1-2.1 { INSERT INTO t1(a) VALUES('xyz'); } {1 {cannot store TEXT value in INT column t1.a}}
- yurishimo 5y agoI listened to a podcast yesterday with the creator of SQLite who said they have billions of test cases running against the project at all times across hardware and software dating back decades at this point. It really is a great project.
- vessel 5y agoThe Untold Story of SQLite With Richard Hipp - CoRecursive Podcast https://corecursive.com/066-sqlite-with-richard-hipp/ https://corecursive.com/066-sqlite-with-richard-hipp/
- krylon 5y agoThis is nice. Very nice. But to be honest, having used SQLite in many hobby/toy projects for ~15 years, I have never ever encountered a type error with it. Stricter handling of types is a good idea, IMHO, but if the alternative had been, say, a reasonable type to represent date/time values, I would have chosen the latter.
- MrBuddyCasino 5y agoIs your usual language strictly typed?
- krylon 5y agoThese days, I am a Go person, so mostly yes, but I used to be a Python, Perl, and Ruby person, and I did not encounter any problems there, either. I think if you expect your database to use certain types, you write your code accordingly. Why would you ever want to insert a BLOB into an INTEGER column? Some kind of data validation/sanitizing is necessary anyway, the database engine being strict about it is just an additional layer of protection, but it shouldn't be one's first line of defense against mistakes. IMHO.
- jatone 5y agoyou and I might not. but bugs happen. and sqlite being so permissive can aggravate the issue.
- krylon 5y agoLike I said, I welcome the option to enforce stricter type checking, and I definitely will make use of it once it becomes available. OTOH, if type safety is a concern, one can already enforce it using CHECK constraints or triggers. But yeah, it's like a seat belt in a car - in order to benefit from it, you have to actually put it on.
- QuadrupleA 5y agoSame here, haven't ran into any problems with the loose typing. I personally love sqlite's dead simple type system though, and its date handling compared to mysql & postgres - a lot of power in a few simple primitives - would hate to see it add a million new types.
- mingodad 5y agoI also proposed once something like "PRAGMA pedantic" where any type conversion would be reported to stderr see the changes and a sample output: https://sqlite.org/forum/forumpost/692ae69237f2537b?t=h https://sqlite.org/forum/forumpost/692ae69237f2537b?t=h https://sqlite.org/forum/forumpost/103d7294464fcde8?t=h https://sqlite.org/forum/forumpost/103d7294464fcde8?t=h
- mingodad 5y agoHere is a sample to test the "pedantic" patch: ==== select "23 % 3", 23 % 3; select "12.3 % 3", 12.3 % 3; select "12 % 2.5", 12 % 2.5; select "23 / 3", 23 / 3; select "12.3 / 3", 12.3 / 3; select "12 / 2.5", 12 / 2.5; create table ta(a text, b integer, c float); select 'insert declared types == value types'; insert into ta(a,b,c) values('a', 1, 2.0); select 'insert declared types != value types text'; insert into ta(a,b,c) values('b', '1', '2.0'); select 'insert declared types != value types'; insert into ta(a,b,c) values('c', 1.0, 2); select 'update declared types == value types'; update ta set a = 'a' ,b = 1, c = 2.0 where a = 'a'; select 'update declared types != value types text'; update ta set a = 'a' ,b = '1', c = '2.0' where a = 'a'; select 'update declared types != value types'; update ta set a = 'a' ,b = 1.0, c = 2 where a = 'a'; select 'update one value declared types != value types'; update ta set b = 1.0 where a = 'a'; select 'update one value declared types != value types'; update ta set a = 49 where a = 'b'; ==== Output default sqlite: ==== 23 % 3|2 12.3 % 3|0.0 12 % 2.5|0.0 23 / 3|7 12.3 / 3|4.1 12 / 2.5|4.8 insert declared types == value types insert declared types != value types text insert declared types != value types update declared types == value types update declared types != value types text update declared types != value types update one value declared types != value types update one value declared types != value types ==== Output of sqlite with "pedantic": ==== 23 % 3|2 FP Remainder received non integer values 3.000000 :: 12.300000 12.3 % 3|0.0 FP Remainder received non integer values 2.500000 :: 12.000000 12 % 2.5|0.0 23 / 3|7 FP Division received non integer values 3.000000 :: 12.300000 12.3 / 3|4.1 FP Division received non integer values 2.500000 :: 12.000000 12 / 2.5|4.8 insert declared types == value types insert declared types != value types text Affinity applied on make record 1 : 1 : D Affinity applied on make record 2 : 1 : E insert declared types != value types Affinity applied on make record 1 : 2 : D update declared types == value types update declared types != value types text Affinity applied on make record 1 : 1 : D Affinity applied on make record 2 : 1 : E update declared types != value types Affinity applied on make record 1 : 2 : D update one value declared types != value types Affinity applied on make record 1 : 2 : D update one value declared types != value types Affinity applied on make record 0 : 3 : B ====
- gigatexal 5y agoThis makes SQLite even better than it already was. I am 100% onboard with this effort.
- bob1029 5y agoThis looks like a reasonable proposal to me. What sort of performance impact could we expect to see when accessing strict tables? Also, is there going to be an ALTER TABLE variant?
- janvdberg 5y agoSide note, Richard Hipp was on this weeks Changelog podcast. Super interesting as always: https://player.fm/series/the-changelog-software-development-open-source/richard-hipp-returns https://player.fm/series/the-changelog-software-development-...
- cryptonector 5y agoYES YES YES PLEASE. I would also like a mode where no type coercion happens.
- pdimitar 5y agoI'm very happy to see this! I'll still keep my CHECK constraints but having the table opt-in STRICT mode is unloading a boulder off of my shoulders. Very grateful to the SQLite team! Kudos for not digging your heels in and trying to accommodate your diverse community. Big respect.
- tehbeard 5y agoIgnoring the side show of "wait it doesn't have types" and "lol it's bad because it's lax on types".... Is having a "STRICT" keyword appended to the end of the CREATE TABLE syntax the best option? I'd have thought this would be a PRAGMA option if ever implemented.
- chacham15 5y agoPRAGMA doesnt enable you to incrementally adopt the feature.
- tehbeard 5y agoHow so? I'd have thought a PRAGMA is sort of a sticky, sometimes persistent flag; and this only affects CREATE TABLE statements so you could toggle it inbetween such statements if your refactoring for it would be large enough to nesesitate doing so in stages? I use sqlite a fair bit but admittedly know little about the layers beneath, and it feels like tagging this feature to the end of CREATE TABLE just means more "magic invocation boilerplate" that might be straying from SQL syntax? Again, not too clued into the deep minuta of SQL so maybe suffixes to the CREATE TABLE are "valid"? This would count similar to engine or charset configuration in a mysql statement?
- chacham15 5y agoIt sounds like you're asking why PRAGMA cant be used to affect the table only during its creation. The main reason for this with SQLite is that SQLite stores the table definition as text. If you run `SELECT sql FROM sqlite_master WHERE type='table'` you can see all the statements that are used to create the tables. Therefore, in order to specify which tables should be strict, you would have to have something in that statement that indicates it. The other option would be to have the flag control all tables (even ones created previously) which prevents incremental adoption.
- Slix 5y agoOne disadvantage is that inspecting the column datatype will no longer hint to the application whether the column contains a date.
- coldacid 5y agoIt would be nicer if this were a per-column constraint rather than a per-table one, but it's very welcome all the same.
- malkia 5y agoWondering if this is going to bring some noticeable performance optimizations apart from the other benefits?
- QuadrupleA 5y agoProbably not - the on-disk storage format still includes the types in the rows (in a very space-efficient form) so this would just add an error check / message rather than accepting a differently-typed value.
- QuadrupleA 5y agoNice to see this. Curious what cases people have encountered where sqlite's loose typing has proved really useful or simplified a design? I always knew about it but basically never used it, just treated tables as though they were strongly typed.
- wruza 5y agoI tried a quick search for “sqlite [dynamic] typ{e,ing} pitfalls”, but got mostly irrelevant results. Can anyone please share common pitfalls of $subj issue? (Apart from obvious “you can insert a mess into a column and get hit by it later”)
- nooorofe 5y agofor me mixed value types killed index, which drastically affected performance
- stolsvik 5y agoIt would be nice if the entire database could be set into strict mode, so that you wouldn't have to specify it on every table.
- hcduytWW 5y agoMy names are Florence L William from Chicago, IL. I work as a customer representative in a mineral company here, was earning a little bit okay $1400 monthly, with my two kids I decided that I need to invest, the taught of my investment came after I meant a guy online who makes me feel comfortable and always talk me into self-employed business, I decide to always seek for his advice and he gave me a broker site where I can invest and have profit within a short period of time, I do really trust him but after I invested into the crypto site I discover he was behind everything and I have lost all my savings to him without knowing how he gets into me and lure me with his sweet fuckin words, he ruined my life and I couldn't be myself anymore. So i decide to seek for help, omg... any attempt i make i get more scammed couldn't figure out who was real and who wasn't and at the end of it all i came up with a decision that nothing on the internet is real again. after 2 months i gave up on recovery the money i sent to broker site by bitcoin payment which is up to $73,992 i was on Spotify trying to get some lonely songs for myself when i came across wizardharry (@) programmer (.) net, it sounded real but i was scared to contact him cause it seems i'm not just lucky with making money on investment maybe i had to work through out my whole lifetime so i ignored but i was in a worker meeting when a discussion lead to bitcoin scam and i heard one of my co-worker saying wizard Harry got her funds back and i ask her how she reached him and she gave me this WhatsApp (+1) 807-808-6168, i reached out to Wizard Harry immediately i got home and we talked for long and i decide to put him to test, to end the whole story, i got more than what i loss on my new blockchain wallet, i was scared at first until he explained to me, a big thanks to the only real recovery hacker online and that's wizard Harry who i have experienced his magic wizard.