of 71 /71
Multiuser databases (Chapter 9 - Kroenke)

Multiuser databases (Chapter 9 - Kroenke )

  • Upload
    fia

  • View
    141

  • Download
    0

Embed Size (px)

DESCRIPTION

Multiuser databases (Chapter 9 - Kroenke ). DBA responsibilities ( Kroenke ). Managing database structure Controlling concurrent processing Managing processing rights and responsibilities Developing database security Provide for database recovery Managing the DBMS - PowerPoint PPT Presentation

Citation preview

Comparisons between C++ and Java (Appendix I)

Multiuser databases (Chapter 9 - Kroenke)DBA responsibilities (Kroenke)Managing database structureControlling concurrent processingManaging processing rights and responsibilitiesDeveloping database securityProvide for database recoveryManaging the DBMSMaintaining the data repository.Problem:Make two copies of the C# university applicationRun each on different machines.In both, locate the same student record to be deleted.Set up breakpoints in the delete buttons click method and step to the stored procedure call in each application.Delete the record in one app.Try to delete the record in the other. You will get a message similar to the following, which contradicts what is on the screen.

Another type of problem:Locate the same student record in both applications and set breakpoints at the ExecuteNonQuery call in the student update forms save button click method.Change the credits to 88 in one and update.Change the credits to 77 in the other. Update one immediately followed by the other.Both windows show what the user entered.Youll see (by going back to the main form and returning to the student form) the 1st update did not stick. Or you can click the Update Student button to see seemingly conflicting informationThe result is what is called a lost update.

Some general classifications of concurrency problems:Lost Update Problem:Figure 9-5 on page 327 of text.Bs update of the item is based on incorrect info (never saw As change)As update lost

Uncommitted dependency problem:B gets and updates PA gets P (or updates P)B encounters a problem and restores the original value it had for PIn database lingo, this is called a rollbackAs future action depends on uncommitted change; or As update negated due to rollbackInconsistent Analysis Problem:Three accounts: A, B, and C: A has $1000, B has $2000; C has $3000Transfer $500 from A to CSum up values in three accountsSum = 0Add As balance to Sum (Sum = $1000)Deduct $500 from A (As balance is now $500)Add Bs balance to Sum (Sum = $3000)Add $500 to C (Cs balance is now $3500)Add Cs balance to Sum (Sum = $6500)timeFinal sum is incorrect.TransactionLogical Unit of Work or a series of actions that must ALL be done or NONE at all. Sometimes called atomic. A transaction is usually delimited by a begin and either a commit or rollback.CommitWrite all changes to the database.Transaction is done.RollbackRestore the database to its status prior to the beginning of the transaction.As if the transaction never started.ExampleDelete a record that is referenced from other locations. Must delete record and all references or do not delete anything.ExampleCreate an order for a customer and update the customer record reflecting the cost of the order. If, for some reason, the application had no access to the customer record, it would need to do a rollback and remove the order.SolutionsPrevent one app from accessing a record if another is about to change it. That is - put a lock on it. When accessing a record that is locked, wait for the resource to be released.The app goes into a wait state until the lock is released, at which point the application resumes at the point at which it went to sleep.Implicit lock Lock placed automatically by the DBMS. Most common.Explicit lockLock placed using a specified command.Lost Update Problem with locksFigure 9-6 on page 328 of text. Assumes explicit locks.Lock granularity: Locks at the database level (large granularity), table level, disk block level, record level, or even field level (small granularity). Large granularity can cause more conflicts but easier to administer. Small granularity is the reverse. Exclusive lockLock item from any type of access. Any application wanting that item must wait until the lock is released.Shared lockAllow read access but not write access until the lock is released.Serializable Transactions: Processing concurrent transactions to produce logically consistent results.ExampleABStart transactionStart transactionPut a lock on x (x is 100)Wait for x (x is 100)Add 100 to x (x is 200)Release lock on xGet x (x is 200)Get lock on yAdd 100 to x (x is 300)Change yCommitProblem with y; abort and rollback (x is reset to 100)B lost its change to x.timeLocks were used, but incorrectly:Two-phased locking:Locking (or growing) phaseacquire locks, release noneRelease (or shrinking) phaserelease locks, acquire none, typically part of rollback or commit.The example in the previous slide did not implement two phased locking.A was allowed to lock x, then release x, then lock y.ABStart transactionStart transactionPut a lock on x (x is 100)Wait for x (x is 100)Add 100 to x (x is 200)Release lock on xGet x (x is 200)Get lock on yAdd 100 to x (x is 300)Change yCommitProblem with y; abort and rollback (x is reset to 100)Does not get x until hereB lost its change to x.timeDeadlock (Deadly embrace) Two activities each waiting for the other to release something.Figure 9-7 on page 329Can involve more than two activities if there is a circular chain of activities, each waiting on the next.Deadlocks have been studied extensively.Impossible to prevent without significant side effects such as forcing all activities to requests ALL locks at the same time or forcing all activities to lock resources in the same order.Algorithms exist to build data structures representing activities and resources and to look for cycles in those structures.

Concurrency control in ADO.NET: [http://msdn2.microsoft.com/en-us/library/22hhd212(vs.71).aspx]Transactions in ADO.NET and SQL ServerSomewhat awkward since .NET is a disconnected architecture but here are some things you can do in the student update form (though, there are other ways):

Add SqlTransaction myTrans; as a class variable in the studentUpdate form.Add myTrans = conStudent.BeginTransaction(); at the beginning of the save buttons click method.Add myTrans as a 3rd parameter to the line creating the SqlCommand object, dbCommand.Add myTrans.Commit(); to the end of the button save click method but prior to conStudent.Close().Step through the two apps and attempt to update the same record. When the first hits ExecuteNonQuery a lock is set. When the other hits ExecuteNonQuery, it waits until the first executes commit.If the first is delayed for too long, the other times out. Note that both apps are still allowed to see the same record and one of them loses its update. Another option is:Keep SqlTransaction myTrans; as a class variable in the student update form.Move myTrans = conStudent.BeginTransaction(); to the form load method after opening the connection.Add myTrans as a 3rd parameter to the line creating the SqlCommand object, dbCommand in each of the form load and save methods.Keep myTrans.Commit(); at the end of the button save click method prior to closing the connection.

Step through as beforeBy itself this does not really change anythingIn the forms load method the call to executenonquery is not blocked. The findStudent stored procedure referenced only retrieves data. Thus, no locks are set. There is a select for update command but SQL Server does not support it. It DOES however, allow you to specify With (XLOCK) as part of the SQL command. Can put this clause after the From clause of the last select command in the findStudent stored procedure. Can also specify With (XLOCK, ROWLOCK) to lock one row only.

NOTE:This example is for illustrative purposes only. There is a serious side effect to locking records when they are retrieved for viewing as it could cause long waits for other applications.Another NOTE:The previous example works well as long as triggers are disabled. If a trigger is enabled for updates, the locks behave in unexpected ways because the trigger can update other records and initiate additional locks, sometimes causing deadlock.Example: If I try to update two different student records, the results can be hard to predict.In management studio, I can right click on the Student table trigger and select disable and the problem is resolved.Processing transactions [http://msdn2.microsoft.com/en-us/library/w97s6fw4(vs.71).aspx]Types of concurrency control [http://msdn.microsoft.com/en-us/library/cs6hb8k4(VS.71).aspx]Pessimistic locking:Locks are issued, the transaction is processed, and locks are released during the commit or rollback (end of transaction). Assume conflicts are frequent and forces synchronization. Locks typically held for longer periods of time.Optimistic locking:transactions proceed unsynchronized and conflicts checked ONLY when commit occurs. If conflict occurs, transaction is redone. Assumes conflicts are rare. Advantage: lock held only during final phase (commit) and locks are held less time. Disadvantage: could force activities to be repeated many times. See Kroenke page 330.See Kroenke page 445. ACID properties of a transaction: Atomic, consistent, isolated, and durable. [http://msdn.microsoft.com/en-us/library/aa719484(VS.71).aspx]Atomic: all or none: If a record is deleted, all references to it must also be deleted. If changes are needed for all customers in a zip code, than all or none of the customers must be updated.Consistent:Constraints that exist prior to a transaction must exist after it. If a student record contains a GPA reflecting course grades, then it must reflect new courses taken that are added to the database.Statement level consistency: All rows affected by an SQL statement are protected against other changes. Example on page 332-333Transaction level consistency: All rows affected by all SQL statements in a transaction are protected. Example on page 332-333.

Isolated: Isolated has different meanings dependent on context. First some definitions:Dirty read: A transaction reads data that has been updated but not yet committed by another transaction. The data could be rolled back and the data that was read would be incorrect.Nonrepeatable read: a transaction rereads data it previously read and finds it has changed due to a commit by another transaction.Phantom reads: Rereads data and finds new records (inserted by a committed transaction) that were not present previously.

Isolation levels define which of these can occur (1992 SQL Standard)See Figure 9-11 on page 333User specifies isolation level and the DBMS creates and manages locks appropriately.The connection objects BeginTransaction method allows the specification of an isolation level as a parameter. Put the cursor on BeginTransaction and press F1 for help to see options. Can also put myTrans in a debug watch window and view its IsolationLevel value.[http://msdn.microsoft.com/en-us/library/system.data.isolationlevel.aspx]

Durable: committed changes are permanent even in case of system or hardware failure. That is, committed transactions are recoverable in case of error.Cursor: a mechanism to identify a single row among a set of rows. See the applyCreditsEarned stored procedure for an example. Its a little like an iterator.Cursor Types:Forward only: Forward scrolling only. Changes to a row are visible if they are ahead of the current cursor position.Static: Creates a copy of the data. Can see its own changes but not those of other transactions. Can also go backward and forward.Keyset: When the cursor is opened the primary key value for each row is saved. All access is through the stored key. Sees updates and deletions by other transaction, but not inserts from other transactions.Dynamic: All committed changes visible. If isolation level allows a dirty read then uncommitted changes are visible.Security:Generally can Grant and Revoke various rights for any user to any view, table, or stored procedure.Protection against unauthorized access to information. Make access easy to those authorized to have it and difficult to those not authorized to have it. User rights. For example, go to SecurityLogins Right click on the userselect propertiesselect User Mapping. Can specify which database to provide access and the type of access. Can do something similar under a database by selecting users in the security folder and looking at the properties of any user.

Or under a database select securityRolesDatabase Roles. Select StudentRole, right click and select properties to see permissions and logins assigned to this role.For each table, view, and stored procedure select properties and add studentrole, making sure to check the checkbox associated with Grant for Select and for View Definition. For stored procedures it will be View Definition only. This provides accessibility to a role which can remain over subsequent semesters. Need only remove and associate student logins to this role each semester.Use of firewalls to separate Internet community from database. Firewalls filter traffic going in and out of an organization. Ideally, it prevents passage of things it considers harmful.Secure Sockets Layer (used in Internet applications). Negotiation between a client and server to establish an encryption scheme and key. Information is encrypted prior to being sent over the Internet.Use of views to hide information from applications.Use of encryption algorithms to encrypt data and transmitted information.Passwords (though these are notoriously problematic because users share them, write them down, use easy-to-guess passwords, send them over unencrypted connections, and infrequently change them.See security guidelines page 337.Making SQL behave differently than was intendedModify the registration form by removing the single quote marks from the sql strings in the btnLocateStudent click method and in the fillListBox method.It still works for correct dataHowever, enter 888888888 or 1=1 into the ID field and locate a student.This is an SQL injection attack. See also page 340.Recovery:What if:A program aborts in the middle of a transaction?The operating system hiccups or crashes?There is a power failure?The disk containing the database experiences a head crash?Errors never occur at convenient times.

Journals (transaction logs):A journal keeps track of every action against a database and includes both the before and after images related to a change.Journal entries are written BEFORE the database is updated (Kroenke, Page 341)Used in the event of recovery and keeps a consistent database state due to the commitment and rollback of transactions.Uses media separate from that used by the database (tapes, disks).Log entry containstransaction IDTimetype of activity (transaction start, update, delete, insert, transaction end)Table nameBefore imageAfter imageExample: Figure 9-17 and text on page 341-342.An application crashesrestore all the before images back to the transactions start.Soft crash: eg. A power failure or an OS crashContents of main memory lostAny buffers containing data to be written are lostState of transactions at the time of crash is unknown.

Undo the transactions that never finishedRedo the transactions that DIDThe journal has that informationBut which transactions? Since when?

Checkpoints:A checkpoint establishes a period of time during which:No new transactions are accepted.All transactions in progress are completed.Any database images remaining in memory are written to the database.A checkpoint record is written to the log file.Database and log are synchronizedPerhaps 3-4 per hour.When transactions must be redone, need only go back to the most recent checkpointHard crashEvent causing the destruction of the media holding the databaseRestore from most recent backupRedo all transactions in the log taken since the last backup.