Wednesday, March 23, 2011

Locking a MySQL database so only one person at once can run a query?

I am having a few issues when people are trying to access a MySQL database and they are trying to update tables with the same information.

I have a webpage written using PHP. In this webpage is a query to check if certain data has been entered into the database. If the data hasn't, then i proceed to insert it. The trouble is that if two people try at the same time, the check might say the data has not been entered yet but when the insert takes place it has been by the other person.

What is the best way to handle this scenario? Can i lock the database to only process my queries first then anothers?

From stackoverflow
  • You're looking for LOCK.

    http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

    This can be run as a simple mysql_query (or MySQLi::query/prepare).

    I'd say it's better to lock specific tables (although you can probably try LOCK TABLES *) that need to be locked rather than the whole database - as nothing will be able to be read. I think you're looking for something like:

    LOCK TABLES items;
    START TRANSACTION;
    INSERT INTO items (name, label) VALUES ('foo', 'bar');
    UNLOCK TABLES;
    

    Or in PHP:

    mysql_query('LOCK TABLES items');
    mysql_query("INSERT INTO items (name, label) VALUES ('foo', 'bar')");
    mysql_query('UNLOCK TABLES');
    
  • You could check if data has been changed before you edit something. In that case if someone has edited data while other person is doing his edit, he will be informed about it.

    Kind of like stackoverflow handles commenting.

  • Read up on database transactions. That's probably a better way to handle what you need than running LOCK TABLES.

  • Manually locking tables is the worst think you could ever do. What happens if the code to unlock them never runs (because the PHP fails, or the user next clicks the next step, walks away from the PC, etc).

    One way to minimize this in a web app, and a common mistake devs do, is to have a datagrid full of text boxes of data to edit, with a save button per row or on the whole table. Obviously if the person opens this on Friday and comes back Monday, the data could be wrong and they could be saving over new data. One easy way to fix this is to instead have EDIT buttons on each row, and clicking the button then loads an editing form, this way they are hopefully loading fresh data and can only submit 1 row change at a time.

    But even more importantly, you should include a datetime field as a hidden input box, and when they try to submit the data look at the date and decide how old the data is and make a decision how old is too old and to warn or deny the user about their action.

Arrays as result type and input for functions

in delphi7 i have a function that i need to return a array as a result type b

"function createsbox(key:tkey):array[0..255] of byte;" this is not allowed it is expecting a "identifyer expected but array found" is the error throw up. seems to work fine if i declare a record type of array but it seems pointless to do this for one function.

From stackoverflow
  • The issue is that you're not allowed to create a new type in a function declaration. But that's what you're doing when you specify the return type as array[0..255] of Byte. Instead, declare a named type, and then use it for the return type:

    type
      TSBox = array[0..255] of Byte;
    
    function CreateSBox(const Key: TKey): TSBox;
    

Session Variable problems when storing an object in my Session

I have a log in page where I valid my users and based on this validation I store their user info in a session variable so I can access it at any time. To do this I am trying to store an instance of one of my dbml generated classes "UserInfo". So I populate the class and then store it in a session variable I call "user"

 UserInfo u = new UserInfo();
    u = dal.RetrieveUser(userID, userPass)
    Session["user"] = u;

The issue I am having with this is it seems to mix up these session variables between users. Or more specifically it always seems to take the information from the first user variable stored for each subsequent user that logs in. So user 1's info is being pulled in for User 2, User 3, etc...

Is my problem that my class "UserInfo" is somehow static? Or what is causing this to happen? My UserInfo class looks like this:

public partial class UserInfo
    {
        ...

EDIT: After further review it seems that my Session variables are in fact working properly but my custom menus are actually the problem.

From stackoverflow
  • Sounds more like an issue with the DAL than the session object. Can you verify that the userID passed each time is different and the RetrieveUser function is using the passed value and not a static one?

    Collin Estes : yeah I checked it and made sure but it is retrieving the right information and creating the session variable correctly. The userID is actually just the value of the text box from the login.
  • Are you testing this using the web client on the same computer or separate computers? For instance, by default FireFox will run in a single process even if you have multiple windows or tabs open. As silly as it sounds, a colleague of mine had not noticed this phenomena when he had the same issue.

Cons for defining logger non-static

Comments for this answer http://stackoverflow.com/questions/212697/how-do-you-reduce-java-logging-boilerplate-code#212753 strongly suggest not to use loggers as instance member variables. I can think of two negative side-effects:
1) superclass logs with the subclass's logger
2) object cannot be serialized (unless marked transient)

But if serializing is not necessary and logging with subclass name is not a problem, is there anything else why it should be avoided? I think it reduces boilerplate code and avoids copy-paste errors while copying logger variable definition from one class to another. Even Spring framework (which I believe has very good coding standards) uses this method.

From stackoverflow
  • Try debugging an error where you see a message generated by the SuperClass class when the error is really being logged in the SubClass class. I've seen several situations where developers create a LoggingUtils class which generates messages which generally duplicate the things which are already baked-in by the logging framework.

    The only real situation I see for using a shared logging instance is something like the Apache commons HttpClient logger httpclient.wire which is shared between several classes for logging the contents of the requests and responses sent through the client. This particular logging situation does not log information for the actual implementation of the package, it logs information about the whole http "transaction".

  • Another, probably minor con: wasted memory, especially when you have lots of instances, each one with its own logger

    martsraits : Log4j (I presume other logging frameworks also) holds a pool of loggers. So only one instance with the same name is created. So memory consumption is the same as with static loggers.
    Ashutosh Singh : if this is con then better to use singelton
    Yoni Roit : @martsraits: No, because your class holds a new reference (pointer) to the pooled instance
  • The major difference asides from the Superclass logging with subclass name, of course, is that you'll have one Logger object per member of your class. Depending on how many classes are using logging, this can be a huge amount of Loggers, so memory bloat may be an issue.

    Plus from an abstract point of view, the logger really does belong to the class and can be shared between all instances, rather than each instance needing its own private copy, so it makes sense to declare it as static. Flipping your question around, what advantages does it have to making it non-static? (Being able to pass getClass() into the getLogger() call instead of passing in the class constant is the only thing I can think of, and that's such a tiny thing).

    martsraits : Log4j (I presume other logging frameworks also) holds a pool of loggers. So only one instance with the same name is created. So memory consumption is the same as with static loggers.
    martsraits : As a pro I also mentioned reducing boilerplate code.
  • If your Logger is an instance member instead of static, the Logger has to be retrieved every time a new object is created. Albeit this overhead is probably insignificant, but it's one disadvantage.

    From a design perspective, Loggers aren't really a property of an object, since they're usually meta-information about your system rather than business information within the system itself. A Logger isn't really part of something like a Car object in the same way an Engine or a Transmission is. Tying Loggers to objects as members (in most cases) doesn't make sense semantically more than anything.

If all my sql server database access is done thru stored procedures.....

If all my sql server database access is done thru stored procedures, and I plan on continuing that practice, is using linq2sql and/or the entity framework for future projects an unnecessary layer of complexity that doesn't add much value?

Related question: is Microsoft trying to steer developers away from relying on stored procs for data access?

From stackoverflow
  • No. LINQ2SQL adds a lot of value in terms of being able to easily map your database entities to classes in your code and work with those classes easily with native langugage constructs. You can easily map the CRUD operations of the generated entity class onto your stored procedures if you want. I do find that some things no longer require stored procedures to work easily and so I have moved away from using them, but you are not forced to. Essentially what LINQ2SQL can do is replace much, if not all, of your DAL, saving you from having to write this code.

    annakata : +1 both sprocs and linq offer more than just data access
  • LINQ-to-SQL supports mapping lots of operations (including CRUD) to stored procedures, but you lose composability - i.e. you can't just add (exp).Where(x=>x.IsActive). One option there is table-valued functions (UDFs) in place of stored procedures that query data; this also presents a more rigid meta model (rather than SET FMT_ONLY ON, which is hit'n'miss).

    That way, your query methods are composable at the database; but note that Entity Framework does not support this, even though LINQ-to-SQL does.

    tvanfosson : I'm using table-valued functions for things like search or browse with filtering. Pass in the filter parameters to the function, get back matching elements from the table. Drop on the table in the designer and I get a function that I can use to replace the data source for a bound control.
    tvanfosson : Actually, doing mostly MVC now, so the bound control thing is sort of moot, but you get the idea...
  • I use Linq2sql for calling my stored procedures as well just because its so fast to generate .net code I can call from my app, its just drag and drop, basically done in seconds. Still I think you need to ask yourself how much time you spend maintaing those stored procedures. If you do you would save a lot of time using linq2sql doing your crud calls. I use sprocs only when doing multiple step operations on the database.

  • Just to address your related question: The benefits of using stored procedures are not as prominent as they once were. Though I would not go as far as saying stored procedures are evil, as some have said in the past (http://www.tonymarston.net/php-mysql/stored-procedures-are-evil.html - this is a very nice article though), I would say that the use of dynamic sql, as long as it's done in a well defined structured way, is perfectly acceptable these days.

    I don't this Microsoft are trying to steer developers away from using stored procs but that dynamic sql should be seen as an acceptable option.

  • You lose the ability to write Linq queries, which is the best part of linq-to-sql.

Type Libraries in Delphi?

What is the best way to save a Delphi Type Library in SVN.

The file changes every time you compile the Application

The file is not saved in a readable form of AscII

It is very difficult to work out what changes have been made from one version to the next

This is a major problem when more than one person is changing the file

QUESTIONS:

1) Should one save an exported ‘IDL’ file in the version control ?

2) Can one covert an ‘IDL ’ into a Delphi type library If so how ?

3) What are the best practices when working with a Delphi type library ?

4) How easy is it get rid of the type library in Delphi2009 datasnap project?

p.s. I am using BDS2006

From stackoverflow
  • In Delphi 2009, this has changed completely. Type libraries are now saved in the project as plain text, RIDL files. These will play nice with source control. DataSnap is also completely changed; you can read about it here, and see a screencast here.

  • There are some good answers to this question at Delphi and COM: TLB and maintenance issues.

  • Prior to Delphi 2009, I would not check in the TLB file but manually put the TLB (and *_TLB.PAS file for reference) into a zip file then force that into version control. When ever I made actual changes to the TLB, I would update the zip file and check it in. The local TLB was always made read/write and ignored by the version control system. This scheme saved me several times when the TLB file would mysteriously no longer compile, I could just close my project, unzip from the zip file, reload the project and continue working.

where should I save a complex MVC application UI state?

I've been having a look at several MVC frameworks (like rails, merb, cakephp, codeignitier, and similars...)

All the samples I've seen are basically plain and simple CRUD pages, carrying all the infr needed in the querystring and the posted field values.

I've got a couple of apps made with some sort of framework built with classic asp.

This framework handles some CRUD stuff a little more complex than the examples I found.

Something like master-detail, filtering by example, paging, sorting and similars.

I have a controller class that it's just a finite state machine, that goes thru diferent states (like new, browse, filter, show, etc.), then performs the appropiate action depending on the event raised and finally retrieves the neede info to the calling page.

To achieve this I have several hidden inputs to keep the state of the web page (like current id, filter criterias, order criterias, previous state, previous event, well, you get the idea)

What do you think would be the finnest approach to achieve this kind of funcionality?

hidden inputs built in the view and used from the controller??? (I guess that would be the equivalent of what I'm doing right now in classi asp)

--

(added in response to tvanfosson)

basically, my question refers to the third category, the context-dependent setting (in respect to the other two categories I agree with you) the info I was storing in hidden fields to store them on the querystring, I guess that when you click on the "next page" you include everything you need to save in the querystring, right? so that piece of query string gets appended in each and every link that performns some kind of action...

I'm not sure, what are the advantages and disadvantages of using the querystring instead of hidden inputs???

From stackoverflow
  • I use different strategies depending on the character of the actual data. Things that are preferences, like default page size, I keep in a Preferences object (table) that is associated with the current logged in user and retrieve from there when needed.

    Persistent settings associated with the current logon, like filter settings for a page, are stored in the user's session. Generally these are things that if a user sets them in the current session they should remain sticky. I think filter settings and visibility are like this. If I filter a list, navigate away from it to drill down into a particular item, then come back to the list, I want my filter settings to be reapplied -- so I make it part of the session.

    Context-dependent settings -- like the current sort column or page number, are controlled using query parameters. Paging and sort controls (links) are built with the appropriate query parameters to "do the right thing" when clicked and pass any necessary query parameters to maintain or update the current context of the control. Using the query parameters allows you to use an HTTP GET, which is bookmarkable, rather than a POST. Using hidden form parameters makes it much harder for the user to save or enter a URL that takes them directly where they want to go. This is probably more useful for sorting than it is for paging, but the principle applies equally.