Noobish PHP Question - Loading Preference-Like Values From Database

Status
Not open for further replies.
I'm goofing around with a PHP site that stores preferences (names + values) in a MySQL table, but I can't figure out a clean way to turn these into into PHP variables.

My database table looks like this...
Code:
setting_name  setting_value
===========================
color         blue
font          helvetica
size          16

My code looks like this...
Code:
while ($dbrow = mysql_fetch_array($dbresult, MYSQL_ASSOC))
	{
	if ($dbrow['setting_name'] == 'color') {$color = $dbrow['setting_value']};
	if ($dbrow['setting_name'] == 'font') {$font = $dbrow['setting_value']};
	if ($dbrow['setting_name'] == 'size') {$size = $dbrow['setting_value']};
	}

Surely there is a better way.
 

flowercrate

Ars Tribunus Militum
2,981
Subscriptor++
I suspect the design of your app and/or the db is flawed. If you can, fix that. Otherwise:

You should use PDO and make use of prepared statements.

Use fetch(PDO::FETCH_ASSOC) and

I'd do a fetch_all and just foreach over it though.


Actually screw that, something is very wrong with that db and the app design. You need to fix that. Seriously.

Why not a "settings" table like this:
Code:
color  font        size
===========================
blue   helvetica   16

If you get that with fetch assoc you'd get a nice named array with the setting names as index.
 

KrispyK

Ars Scholae Palatinae
911
The database structure is fine - key value pairs are perfectly suited for configuration variables.

In your code, you just need to do the following:
Code:
$$dbrow['setting_name'] = $dbrow['setting_value']};
this gives you
Code:
$color = "blue";
$font = "helvetica";
...
The key is the double $$. But obviously, you shouldn't be doing that, you don't want a ton of variables lying around all over the place.

Better to have
Code:
$config[$dbrow['setting_name']] = $dbrow['setting_value'];
this gives you
Code:
$config['color'] = "blue";
$config['font'] = "helvetica";
...
And even better to wrap it all inside a self-contained class (not depicted here) so you can do
Code:
Settings::get('colour');
Settings::set('colour','red');
 

flowercrate

Ars Tribunus Militum
2,981
Subscriptor++
wallinbl":yygiarw3 said:
needle":yygiarw3 said:
Actually screw that, something is very wrong with that db and the app design. You need to fix that. Seriously.
The schema is perfectly fine. Seriously. Not sure why you'd prefer to take what's essentially a hashtable/dictionary and spread it out into 50 columns/variables.
I guess I don't see why having the variables dynamically named after the setting name is useful. KrispyK's solution actually does what OP's code sample does, dynamically. But why would you want to do that? If you want to address those variables later, you'd need to know what they're called. But if you know what they're called, why not set up the table like I proposed?
 

CanSpice

Ars Tribunus Angusticlavius
7,147
needle":3axnttb9 said:
But if you know what they're called, why not set up the table like I proposed?
Nobody said he knew what the options are called. The nature of these things is that you're always going to have another option to add, and if you turned them into columns you'd have to alter the database table, whereas if you just treat the options table as a key/value pair you just add a new row.

Adding a new row is always preferable to altering a table.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
Do you really want a table with 100+ columns?

Key value tables are standard and, as per syntax suggested prior quite nice to actually work with when handled properly. You can cache the results (session or memcache, etc) and only load the ones referenced. With a decent API you can dynamically fetch any you haven't used before, so real overhead is limited to what's being used.

It isn't perfect of course, but then neither is php, and you could over do it if you go crazy.
 
If the set of keys is static and not outrageously large, give each its own column. That way you can ensure data integrity on a per-column basis (for example, make sure that values are of the right type and enforce non-nullity selectively), it's easier to use an ORM to auto-populate a correctly typed object, and you can more cleanly handle multiple configurations. There's basically no downside to using many columns instead of many rows. If the set of keys is dynamic or very large, you have no choice but to use a general key/value table.

CanSpice":3j9uuei5 said:
Nobody said he knew what the options are called. The nature of these things is that you're always going to have another option to add, and if you turned them into columns you'd have to alter the database table, whereas if you just treat the options table as a key/value pair you just add a new row.

Adding a new row is always preferable to altering a table.
If you have to change the code to support a new setting, you may as well alter the table. It's trivial and you get all the benefits of properly structured data with enforced integrity instead of a fast-and-loose bag of stringly typed shit. (Then again, the OP is using PHP so maybe (s)he is too numb to notice any more pain.)
 

flowercrate

Ars Tribunus Militum
2,981
Subscriptor++
Solomonoff's Secret":3c7cou5e said:
CanSpice":3c7cou5e said:
Nobody said he knew what the options are called. The nature of these things is that you're always going to have another option to add, and if you turned them into columns you'd have to alter the database table, whereas if you just treat the options table as a key/value pair you just add a new row.

Adding a new row is always preferable to altering a table.
If you have to change the code to support a new setting, you may as well alter the table. It's trivial and you get all the benefits of properly structured data with enforced integrity instead of a fast-and-loose bag of stringly typed shit. (Then again, the OP is using PHP so maybe (s)he is too numb to notice any more pain.)
Yeah, that was what I meant. I still don't get the value of having the variables named after the setting. Why?
 
Don't think so literally! You want a single array - $config - that stores all keys and values.

Code:
while ( $dbrow = mysql_fetch_array($dbresult, MYSQL_ASSOC) )
    $config[$dbrow['setting_name']] = $dbrow['setting_value'];
}

That's much easier to maintain. Then when you realize you need to see a list of all your settings it is as simple as...

Code:
echo '<pre>';
print_r($config);
echo '</pre>';

...except you'll be smarter than that. You'll write a quick and dirty function to do it for you...

Code:
function debug($var)
{
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Solomonoff's Secret":3k7g923h said:
If the set of keys is static and not outrageously large, give each its own column. That way you can ensure data integrity on a per-column basis (for example, make sure that values are of the right type and enforce non-nullity selectively), it's easier to use an ORM to auto-populate a correctly typed object, and you can more cleanly handle multiple configurations. There's basically no downside to using many columns instead of many rows. If the set of keys is dynamic or very large, you have no choice but to use a general key/value table.
Every database has a column limit, and they're typically not that hard to hit. MySQL/InnoDB only supports 1000 columns (and like 8000 bytes) in a single row, which really is not very much.

If you need strongly typed key-values, then create multiple tables. You can use triggers and a common key table to prevent a key being assigned multiple values, if you feel that's necessary.

Of course, I probably wouldn't store global configuration values in the database. I would store them in a config file on disk.

If you have to change the code to support a new setting, you may as well alter the table. It's trivial and you get all the benefits of properly structured data with enforced integrity instead of a fast-and-loose bag of stringly typed shit.
Actually, it's not trivial because ALTER TABLE is not ACID-compliant in MySQL.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
topham":jry7kox8 said:
You can cache the results (session or memcache, etc) and only load the ones referenced. With a decent API you can dynamically fetch any you haven't used before, so real overhead is limited to what's being used.
While caching in-memory what ought to be read-only is a good idea, I shudder to think about the application that has so many config values that lazy-loading is a necessary optimization.
 
LordHunter317":xxwqk7t2 said:
Every database has a column limit, and they're typically not that hard to hit. MySQL/InnoDB only supports 1000 columns (and like 8000 bytes) in a single row, which really is not very much.
And that's why I said that if there are very many values, you can't store them in separate columns. I doubt your average PHP-MySQL app would need even half that many values.

If you need strongly typed key-values, then create multiple tables. You can use triggers and a common key table to prevent a key being assigned multiple values, if you feel that's necessary.
That sounds way more complex than the other options here, which means it shoudl be a last resort.

Actually, it's not trivial because ALTER TABLE is not ACID-compliant in MySQL.
If you're referring to the fact that it commits the transaction, if you're doing a build and redeploying the app, how is committing a transaction an issue?
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Solomonoff's Secret":3e3dqsqe said:
LordHunter317":3e3dqsqe said:
Every database has a column limit, and they're typically not that hard to hit. MySQL/InnoDB only supports 1000 columns (and like 8000 bytes) in a single row, which really is not very much.
And that's why I said that if there are very many values, you can't store them in separate columns. I doubt your average PHP-MySQL app would need even half that many values.
It's silly to have such a limitation when resolving it takes only a few more CREATE TABLE statements up front.

That sounds way more complex than the other options here, which means it shoudl be a last resort.
It's N tables versus one table, which should hardly be a big deal. Using a trigger to limit key names is more complicated, but not really so. Create a view that unions all the key-value tables together, then the psuedocode for the trigger is:
Code:
SELECT key FROM all_keys_view WHERE key = NEW.key;
IF FOUND THEN
     RAISE ERROR 'Key already exists';
ELSE
   RETURN NEW;
END IF;
(I don't know the MySQL syntax, but that's basically the PostgreSQL syntax).
But honestly I'm not sure the trigger is critical, given that the PHP code has to explicitly query the right table anyway. My guess is you can find servicable code online somewhere.

Actually, it's not trivial because ALTER TABLE is not ACID-compliant in MySQL.
If you're referring to the fact that it commits the transaction, if you're doing a build and redeploying the app, how is committing a transaction an issue?
It means going backwards if there's a problem during the upgrade is rather difficult, as you just can't issue a ROLLBACK anymore. It also requires a full copy of the table and locks it from all other concurrent writes. For global settings, not such a big deal. For per-user settings, that can be a big deal.

Altering a table is fine when it's truly necessary, but you really should try to avoid a design that requires them. Especially when the alternative is just a few extra tables.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
LordHunter317":3dzb9w31 said:
topham":3dzb9w31 said:
You can cache the results (session or memcache, etc) and only load the ones referenced. With a decent API you can dynamically fetch any you haven't used before, so real overhead is limited to what's being used.
While caching in-memory what ought to be read-only is a good idea, I shudder to think about the application that has so many config values that lazy-loading is a necessary optimization.
You've never worked with a large project written in php to run under a web server, have you? Anything you don't cache has to be retrieved from the database on every page load. Relying on the database cache is a fools errand as its quite common to not have enough control of the database to even influence the caching.
If you aren't using APC or it's equivalent you are compiling every php file on load, so even settings files are an issue, etc.

Php is an easy environment to create exhorbitant overhead.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
topham":240jqlj6 said:
Anything you don't cache has to be retrieved from the database on every page load. Relying on the database cache is a fools errand as its quite common to not have enough control of the database to even influence the caching.
I'm aware. That doesn't justify the value of lazy-loading configuration values. Why would I want to add another database round-trip time to my page latency for values that can be trivially held in-memory for the entire life of my application and shouldn't change particularly often (if ever)? As time-space trade offs go, lazy-loading seems like the one wrong to make here. Query all of them once, stuff them in memcached (or wherever), and forget about them.
 
LordHunter317":2oto99lh said:
It's silly to have such a limitation when resolving it takes only a few more CREATE TABLE statements up front.
Sure, I'm not arguing against doing that on principle - only that I'd look for the simplest solution initially if there were no reason to believe I'd need the more complex setup. If the code and schema will have to change anyway, a single table -> multi table refactor isn't a big deal.

It's N tables versus one table, which should hardly be a big deal. Using a trigger to limit key names is more complicated, but not really so. Create a view that unions all the key-value tables together, then the psuedocode for the trigger is:
Code:
SELECT key FROM all_keys_view WHERE key = NEW.key;
IF FOUND THEN
     RAISE ERROR 'Key already exists';
ELSE
   RETURN NEW;
END IF;
(I don't know the MySQL syntax, but that's basically the PostgreSQL syntax).
But honestly I'm not sure the trigger is critical, given that the PHP code has to explicitly query the right table anyway. My guess is you can find servicable code online somewhere.
That is increased complexity and it has to justify its weight.

It means going backwards if there's a problem during the upgrade is rather difficult, as you just can't issue a ROLLBACK anymore.
Pretty much all my releases involving database updates require schema changes so one more doesn't introduce much pain. But if schema changes are rare, you have a point. (Or switch to a real database.)

It also requires a full copy of the table and locks it from all other concurrent writes. For global settings, not such a big deal. For per-user settings, that can be a big deal.
With PostgreSQL, alters are relatively painless. With MySQL, changing a medium-sized column from nullable to not null can take an hour. The lesson is to choose the correct tool, not to unnecessarily paint yourself into a corner.
 
vherrera0079":2nuwtnrc said:
DBA review,
Institutional incompetence. I hate, hate, hate it when separate teams manage the apps and database. It means app developers go as far out of their way as possible to avoid schema changes and end up coding some incredible hacks, when schema changes are the cleanest solution. I'm lucky to not have to deal with that shit as I do everything myself.

new Liquibase version. Everyone having to pull the new version. For a stupid config value.
You need that to add a new config setting even if you're issuing an insert and not an alter, no?

You're right that the database does introduce some complexity overhead that a flat file doesn't, which is why I agree that you only want to add global config to it in unusual situations.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
ShuggyCoUk":1tly5zkt said:
If its so simple it fits in one row of a single table dedicated to the purpose why on earth not just use a file? You get version control, easy local testing and support for more complex types (albeit by dropping into something like XML,YAML,JSON etc)
And you lose the simple case of having an application interface to update it, unless you tie your applications to your version control. Ugh.

I'm split on the whole thing in truth, I've implementated config files, key-value tables, even used db columns, in the end the only method I would really avoid is the column based method. In most of the environments I've worked in adding columns is more in depth and causes excessive workload.
(doesn't make it wrong, but the path of least resistance is generally much easier)
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
topham":2ryt4i0s said:
ShuggyCoUk":2ryt4i0s said:
If its so simple it fits in one row of a single table dedicated to the purpose why on earth not just use a file? You get version control, easy local testing and support for more complex types (albeit by dropping into something like XML,YAML,JSON etc)
And you lose the simple case of having an application interface to update it, unless you tie your applications to your version control. Ugh.

I've seen no decent editor without at least rudimentary support if only by macros.

Surely you want someone to add a commit message to the change explaining why it's being done if you want the file in version control so I'm not really seeing the problem with using a file.

If you edit the same file often enough then script the commit...
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Solomonoff's Secret":3gxqbk3a said:
LordHunter317":3gxqbk3a said:
It's silly to have such a limitation when resolving it takes only a few more CREATE TABLE statements up front.
Sure, I'm not arguing against doing that on principle - only that I'd look for the simplest solution initially if there were no reason to believe I'd need the more complex setup.
First, I'm not sure why you think continued ALTER TABLE operations is less complex than creating a few extra tables upfront (and maybe a trigger) and then doing INSERT/DELETES on them. It's rather apparent you don't understand the cost of managing these operations, nor their cost in terms of database execution time. Modifying a table definition is generally a v. expensive operation and generally should be avoided whenever possible[2].

More importantly though, your solution is only simpler if we can assume the number of configuration values is bounded, and they have meaningful types in the database. Assuming the former isn't a good idea, as these number of required values tends to grow over time as the code gets more complex[1]. The values in the OP all appear to be CSS properties, so it's pretty easy to see how that could grow rapidly. It's especially true if the application supports plugins or other extensible functionality where the number simply cannot be known. As an example, my completely fresh installation of Firefox 12 had over 1500 configuration values.

Plus, I'm not sure what data typing in the database really adds here. MySQL doesn't come with native support for validating CSS colors, font names, or font sizes. It would obviously be possible to add such support (at least for the colors and sizes) but an awful lot of work. All of the configuration data I've ever stored has a similar nature: umasks, user names, hostnames, URLs, base64-encoded API keys, SSL cipher selections, IP addresses, paths, random enumerated strings (e.g., 'a' or 'b'). For a lot of those things, only the application can do the validation, so data store type-safety doesn't add a whole lot. And the application's validation may be as simple as, "Take the value as-is and try to use it, throwing an error when it fails". For many of the things I mentioned, that's all you can do!

It also requires a full copy of the table and locks it from all other concurrent writes. For global settings, not such a big deal. For per-user settings, that can be a big deal.
With PostgreSQL, alters are relatively painless.
Add a column is painless in PostgreSQL if it can default to NULL. Otherwise, you still have to lock the table from all other concurrent writes. That includes altering/adding a NOT NULL constraint to a column. Rebuilding a table is a slow operation, so it's not something you want to do on a busy and/or big table unless you must. It is not a great idea to pick a design where this is your planned upgrade path.

[1] Unless you're a GNOME developer and you're going to delete them all eventually, I suppose.

[2] Even when it is necessary, it is frequently faster, safer, and less painful to create a new table and rename, even though that has ugly costs like requiring all stored procedures and views that reference the table to be recreated. This is true even on "real" databases like Oracle and PostgreSQL.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
topham":3me4s93b said:
ShuggyCoUk":3me4s93b said:
If its so simple it fits in one row of a single table dedicated to the purpose why on earth not just use a file? You get version control, easy local testing and support for more complex types (albeit by dropping into something like XML,YAML,JSON etc)
And you lose the simple case of having an application interface to update it,
I don't see why storing it in a database makes building a preferences UI easier, even in PHP? I understand that the PHP execution model makes guarding against concurrent writes to a file difficult, but I also don't think that's the reason for your objection.

unless you tie your applications to your version control. Ugh.
And I definitely don't see how version control has anything to do with it? Surely, the only thing you version control as a developer is the default / example configuration file?
 
LordHunter317":h7mbbt14 said:
First, I'm not sure why you think continued ALTER TABLE operations is less complex than creating a few extra tables upfront (and maybe a trigger) and then doing INSERT/DELETES on them.
You have to select from multiple tables and possibly join them together. There's a reason tables can store more than one column: it's simpler and easier to store values that are part of the same logical entity and in one-to-one correspondence together.

It's rather apparent you don't understand the cost of managing these operations, nor their cost in terms of database execution time. Modifying a table definition is generally a v. expensive operation and generally should be avoided whenever possible[2].
A configuration table, which will undoubtedly store at most in the hundreds or low thousands of values, is incredibly fast to alter even in MySQL. If done during a release, there's no harm in stop-the-world locking. Database execution time is irrelevant because the data size is incredibly small, and in fact, the more important runtime cost would be lower (although trivially so) if data is stored in one row as opposed to in one row each of many tables joined together.

More importantly though, your solution is only simpler if we can assume the number of configuration values is bounded, and they have meaningful types in the database. Assuming the former isn't a good idea, as these number of required values tends to grow over time as the code gets more complex[1]. The values in the OP all appear to be CSS properties, so it's pretty easy to see how that could grow rapidly. It's especially true if the application supports plugins or other extensible functionality where the number simply cannot be known. As an example, my completely fresh installation of Firefox 12 had over 1500 configuration values.
That's why I qualified what I said. I don't know more about the OP's usage pattern than the OP stated. There could be 10 values or 1000.

Plus, I'm not sure what data typing in the database really adds here. MySQL doesn't come with native support for validating CSS colors, font names, or font sizes. It would obviously be possible to add such support (at least for the colors and sizes) but an awful lot of work. All of the configuration data I've ever stored has a similar nature: umasks, user names, hostnames, URLs, base64-encoded API keys, SSL cipher selections, IP addresses, paths, random enumerated strings (e.g., 'a' or 'b'). For a lot of those things, only the application can do the validation, so data store type-safety doesn't add a whole lot. And the application's validation may be as simple as, "Take the value as-is and try to use it, throwing an error when it fails". For many of the things I mentioned, that's all you can do!
Yeah, for CSS in general it would be a pain to validate in the database. However, you could at least validate purely numerical or enum values (although most numerical values also specify units, which throws a wrench in things - you could have a numerical column for the numerical value and an enum column for the unit but that might be more work than it's worth).

Add a column is painless in PostgreSQL if it can default to NULL. Otherwise, you still have to lock the table from all other concurrent writes. That includes altering/adding a NOT NULL constraint to a column. Rebuilding a table is a slow operation, so it's not something you want to do on a busy and/or big table unless you must. It is not a great idea to pick a design where this is your planned upgrade path.
All this is irrelevant for a tiny configuration table.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Solomonoff's Secret":2kuykgpx said:
That's why I qualified what I said. I don't know more about the OP's usage pattern than the OP stated. There could be 10 values or 1000.
Which is rather the whole problem! "Qualifying" your advice by saying it's only applicable in certain situations doesn't change the fact it's bad advice and of questionable relevance in the first place. Despite your qualification, it's not at all apparent that you are fully aware of the problems and limitations of your solution. Most importantly, it's not apparent that you understand the general-purpose solution, nor why it is superior even in the case that your solution covers.

Unfortunately, it's plainly apparent that you want to continue to ignore the issues regardless of what anyone says. As such, I don't really see any point in continuing this discussion with you, as you've already tautologically decided your solution is "good" despite its problems. Therefore, I don't really see any value in discussing this with you any further. I'm clearly incapable of changing your mind.

There's a reason tables can store more than one column: it's simpler and easier to store values that are part of the same logical entity and in one-to-one correspondence together.
But it is entirely unreasonable to assume either of these things. Seriously, it's like you've never looked at a configuration file before!

A configuration table, which will undoubtedly store at most in the hundreds or low thousands of values, is incredibly fast to alter even in MySQL. If done during a release, there's no harm in stop-the-world locking. Database execution time is irrelevant because the data size is incredibly small, and in fact, the more important runtime cost would be lower (although trivially so) if data is stored in one row as opposed to in one row each of many tables joined together.
The argument, "My solution can't scale so its performance is irrelevant" doesn't make your solution look good against the general-purpose solution that does scale. Nor does a software upgrade inherently justify any DB operation you feel like.

All this is irrelevant for a tiny configuration table.
But not irrelevant in the general case, which is pretty much the only reason I'm discussing this with you. Unfortunately, you don't seem to care about the general case, so I don't see any point in wasting my time further.
 
:rolleyes: More pointless and disingenuous arguments from the guy who can't handle a discussion.

LordHunter317":7ta7it57 said:
Which is rather the whole problem! "Qualifying" your advice by saying it's only applicable in certain situations doesn't change the fact it's bad advice and of questionable relevance in the first place.
So it's a bad solution in the most common case (which the OP implies), where you don't have hundreds of configuration values and where they're stored flat (not in a hierarchy or any other structure)?

Despite your qualification, it's not at all apparent that you are fully aware of the problems and limitations of your solution.
Funny, I described the problems and limitations upfront. It's not my fault that you can't read.

Most importantly, it's not apparent that you understand the general-purpose solution, nor why it is superior even in the case that your solution covers.
The general purpose solution is a structure that mirrors the structure of data in the problem domain. In full generality, there might be complex dependencies between values, multiple values for a single setting, etc. that require more complex table structures. But it's entirely silly to talk about such a situation when the OP has given no indication that any of it applies. The only reasonable thing to do is to give the best solution to the most likely situation and qualify it so that the OP knows whether it applies.

Unfortunately, it's plainly apparent that you want to continue to ignore the issues regardless of what anyone says. As such, I don't really see any point in continuing this discussion with you, as you've already tautologically decided your solution is "good" despite its problems. Therefore, I don't really see any value in discussing this with you any further. I'm clearly incapable of changing your mind.
I have no problem ending this discussion as it's devolving into name-calling and pedantry, as is inevitable with you. You have no interest in helping the OP - only harrassing people here.

But it is entirely unreasonable to assume either of these things. Seriously, it's like you've never looked at a configuration file before!
Again, it's ridiculous to assume that the OP has a hierarchical or other non-flat configuration structure when the OP gave no indication of such. In fact, the OP's proposed solution was a flat key/value table, implying that each key has a single value and that all are part of the same configuration entity.

The argument, "My solution can't scale so its performance is irrelevant" doesn't make your solution look good against the general-purpose solution that does scale.
Fortunately I wasn't making that argument. A software engineer is an engineer - someone who designs solutions that work well within certain constraints. Apps that need even hundreds of configuration options are few and far between, and I doubt their developers would ask for basic advice on config file handling on Ars. But we don't know for sure, which is why I explicitly stated the limitation of my approach so the OP can make the determination. In fact, it would be nice for the OP to reply with the exact constraints of his/her situaiton.

Nor does a software upgrade inherently justify any DB operation you feel like.
But it does justify issuing trivial alters on small tables, which would take small fractions of a second and have virtually no drawback.

But not irrelevant in the general case, which is pretty much the only reason I'm discussing this with you. Unfortunately, you don't seem to care about the general case, so I don't see any point in wasting my time further.
I don't care about the general case because the OP doesn't care about the general case. You're going off on a tangent to quench your thirst for irrelevant arguments.
 
Why, because you have to alter the table to add a config setting? Altering is trivial and instant and allows you to enforce data integrity (to a degree - even if you can't validate all the values, a simple not null constrant is very valuable). If you're adding a config setting, you're going to be changing the database either way - either with an insert or an alter and update - and if you're changing the code and updating the database anyways, what's the harm of running an alter? Basically all of the theoretical considerations mentioned above (locking, slowness, etc.) are irrelevant in this case - the only ones that hold any water are:
* a DBA would have to review an alter statement but not an insert - if this is an issue, your organization has some serious issues
* it's harder to roll back because not all updates are transactional - in practice I suspect this is a minor issue if the update script is properly tested, and a manual rollback procedure could easily drop the column

Analogously, would you rather store a program's data in a more general key/value map or a more specific data structure with named fields (struct, class, etc.)? You're essentially making the argument that it's better to use maps so that when your data changes, you don't have to update your struct/class/whatever. I guess that's the JavaScript approach, where any object can have any property, but it makes it difficult to keep track of what properties should be defined and to enforce that they are defined.
 

CanSpice

Ars Tribunus Angusticlavius
7,147
Well, databases have a limit to the number of columns you can have. Postgres has a limit between 250 and 1600, depending on the table type. MySQL has a row size limit of 65,535 bytes and 4096 columns. While you might think this is a fairly high limit for the number of configuration options a program might have, it's definitely a limit that you're imposing right from the start with your design. Use rows for configuration options and you don't have this problem (if you have hundreds of gigabytes of configuration options you have other issues).

And yes, having columns means you can do some rudimentary data type checking, but realistically, what does this get you? You need to do validation of your configuration options anyhow within your application.

Altering database schemas shouldn't be something one should get into the habit of doing. It's dangerous business, and can lead to database corruption and outages if you're not careful.
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
You can enforce typing without having to expand the table for each new setting:

Code:
+--------------+---------+--------+--------+------+
 Setting       | boolean | string | int    | etc  |
+--------------+---------+--------+--------+------+
 Color         |         | Blue   |        |      |
 timeout       |         |        | 900    |      |
 save_password | 1       |        |        |      | 
+--------------+---------+--------+--------+------+

You need to know what datatype a given preference is when grabbing it's value, and you can't enforce anything restricting null values, but it does accomplish typing and you only need to alter the table if you need to add another datatype.
 
CanSpice":271imf7x said:
Well, databases have a limit to the number of columns you can have. Postgres has a limit between 250 and 1600, depending on the table type. MySQL has a row size limit of 65,535 bytes and 4096 columns. While you might think this is a fairly high limit for the number of configuration options a program might have, it's definitely a limit that you're imposing right from the start with your design. Use rows for configuration options and you don't have this problem (if you have hundreds of gigabytes of configuration options you have other issues).
I would be comfortable with these limits for pretty much all apps I've developed. The important thing is that you understand your needs and find a solution that works for them - anything more is over-architecture.

And yes, having columns means you can do some rudimentary data type checking, but realistically, what does this get you? You need to do validation of your configuration options anyhow within your application.
It means that if you go to update the configuration, the error gets found immediately and it's easier to roll back the change - by the time the app sees it, it's already been committed.

Altering database schemas shouldn't be something one should get into the habit of doing. It's dangerous business, and can lead to database corruption and outages if you're not careful.
Maybe in general, but how does that apply to the particular case of adding a column to a tiny table during an application update?
 
C0rinthian":29he4owq said:
You can enforce typing without having to expand the table for each new setting:

Code:
+--------------+---------+--------+--------+------+
 Setting       | boolean | string | int    | etc  |
+--------------+---------+--------+--------+------+
 Color         |         | Blue   |        |      |
 timeout       |         |        | 900    |      |
 save_password | 1       |        |        |      | 
+--------------+---------+--------+--------+------+

You need to know what datatype a given preference is when grabbing it's value, and you can't enforce anything restricting null values, but it does accomplish typing and you only need to alter the table if you need to add another datatype.
You're trying to reinvent the concept of a database table within the database instead of just using a table the way it was meant to be used, leading to a more awkward and convoluted data model and one that almost certainly won't be easy to map with an ORM or work with manually in the code. Furthermore, there's nothing stopping you from storing values in incorrect columns, just as you could store invalid numbers in a single varchar column, so I don't think this structure buys you anything.
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
LordHunter317":2fwowllo said:
That's even more difficult to query and constrain, though at least it scales with the number of keys. Why do people try to avoid adding tables to relational databases so much? Why do people try to store variant types in relational databases in such convoluted fashions?

I have to work with a db like that on a daily basis and I fucking hate it. But it does exist.
 

Dracorat

Ars Tribunus Militum
2,798
Assuming you want type enforcement in the database, I'd go with (but a bit ugly) something like:

Code:
CREATE TABLE MySchema.IntValues
(
  TableKey INT PRIMARY KEY,
  KeyId INT,
  Val INT,
  CONSTRAINT UNIQUE(KeyId)
);

CREATE TABLE MySchema.CharValues
(
  TableKey INT PRIMARY KEY,
  KeyId INT,
  Val VARCHAR(3000),
  CONSTRAINT UNIQUE(KeyId)
)

CREATE TABLE MySchema.Keys
(
  TableKey INT PRIMARY KEY,
  KeyName VARCHAR2(98),
  TypeName VARCHAR2(98),
  CONSTRAINT UNIQUE(KeyName)
)

CREATE OR REPLACE PROCEDURE MySchema.SaveValue(InKey IN VARCHAR2, InVal IN VARCHAR2)
  KeyType VARCHAR2(98),
  KeyIdentifier INT
AS
BEGIN
  SELECT Lower(TypeName), TableKey INTO KeyType, KeyIdentifier FROM MySchema.Keys WHERE KeyName = InKey;
  CASE
   WHEN TypeName = 'int' THEN 
     BEGIN
       INSERT INTO MySchema.IntValues (KeyId, Val) VALUES (KeyIdentifier, CAST(InVal) AS INT);
     EXCEPTION
       WHEN DUP_VAL_ON_INDEX THEN
         UPDATE MySchema.IntValues SET Val = InVal WHERE KeyId = KeyIdentifier;
     END;
   WHEN TypeName = 'string' THEN 
     BEGIN
       INSERT INTO MySchema.CharValues (KeyId, Val) VALUES (KeyIdentifier, InVal);
     EXCEPTION
       WHEN DUP_VAL_ON_INDEX THEN
         UPDATE MySchema.CharValues SET Val = InVal WHERE KeyId = KeyIdentifier;
     END;
  -- etc for all supported types
  END CASE;
END;

CREATE OR REPLACE PROCEDURE MySchema.GetValue(InKey IN VARCHAR2)
AS
BEGIN
  SELECT 
    COALESCE(B.Val, CAST(C.Val) AS VARCHAR2(98))
  FROM
    MySchema.Keys A
    LEFT JOIN MySchema.CharValues B
      ON A.TableKey = B.KeyId
    LEFT JOIN MySchema.IntValues C
      ON A.TableKey = C.KeyId
  WHERE A.KeyName = InKey
END;

(I probably have a logic error or two in there, but that's my 5 minute slap-an-example-together)

However, I recommend that instead, you store everything in the database as a VARCHAR2 (or whatever your database uses as a CHAR column) and cast it in the program handling exceptions as appropriate there. (Meaning the example table in the OP is perfectly fine for this task.)
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I really wish some databases came with KVP support baked in.

I'm happy for that to be done behind the scenes by a series of per type tables plus the associated meta tables defining 'fields', SP for inserts, no 'variant' select support (you can only get a single field at a time is actually fine).

It just seems wrong to have to re implement the wheel every time (in the same way adding history tables and triggers by hand is just daft)

There are a whole bunch of applications where KVP is genuinely the right thing to do, I admit possibly not as frequently as some people think but they do exist.
 
Status
Not open for further replies.