In my Lua application, I am trying to create a utility function that sets a specific user data. It uses this format: setUserData(int UID, string COLUMN_NAME, mixed ROWVALUE)
It saves the data in a MySQL database.
I’m not sure how to create the column (if it doesn’t exist) and detect the type of the value (TEXT, tinyint, VARCHAR etc) to set the column.
Would it be easier and better to always set the column as a TEXT type? If not, how can I detect and create?
It very much depends on the contract of your
setUserDatafunction. If you expect users to always provide the same value type for a given column name, you might always derive some aspects of the column type from that, in particular whether it consists of characters, an integer or a floating point number. You could then choose to select the column type of maximal size for the given data, i.e.LONGTEXT,DOUBLEorBIGINT. Doing so might require more memory in the database than would strictly be neccessary, but if there really is nothing you know about the data passed to that function, you cannot rule out the possibility that all that space might be neded for some other value in the same column.An alternative approach would be to always choose the smallest data type from a given family. When inserting new data into an existing column, you’d have to look out for truncation warnings, and when you see them, you could enlarge the column type accordingly.
For many applications, storing everything as character will be the simplest solution. But a
LONGTEXTis far more complicated than a simple column type likeTINYINT, so you’ll have to pay both in terms of memory requirements and performance. AVARCHARisn’t as bad, so if you do the auto-enlarging suggested in the previous paragraph, the penalty will be less severe.Behaviour might also be slightly different when you store everything as text, independent from the native type in LUA: when you enter a number as
'01234', it will compare unequal to'1234'. Whether this is desirable or not depends on your application, and might be a good indication whether storing your data as text is a good idea. As long as the LUA side will always use the same data type, there shouldn’t be any difference, as the same data type will be converted to text in the same way every time.