简体   繁体   中英

Database to store list of dictionaries

I need a way to store the following structure in a database. The context is that I have a table which includes a list of resources and I need to be able to lock this table when I conduct operations to prevent concurrent writes.

ProjectID: abcd Lock: False Resources: [ { Resource: CPU AvailableQuota: 50 UsedQuota: 35 },{ Resource: StaticIps AvailableQuota: 70 UsedQuota: 45 } ]

I have thought of putting it in a MySQL database but can't think of an appropriate way to nest the list so that we can lock on the 'ProjectId' field.

Any pointers to a database / datastore that allows this form of datastructure nesting?

In MySQL you could build a table with the following columns.

ProjectId         VARCHAR(100)
ResourceName      VARCHAR(100)
AvailableQuota    INT
UsedQuota         INT

The ProjectId and ResourceName columns are the compound primary key.

Then you can can use dbms transactions to serialize the use of data in your table. If all you want to do is read, but not change, your resources you can do

   BEGIN TRANSACTION;
   SELECT ResourceName, AvailableQuota, UsedQuota
     FROM table
    WHERE ProjectId = 'whatever'
     LOCK IN SHARE MODE;
      /* do whatever you need to do */
   COMMIT;

On the other hand if you need to change the data, you can do this sort of thing.

   BEGIN TRANSACTION;
   SELECT ResourceName, AvailableQuota, UsedQuota
     FROM table
    WHERE ProjectId = 'whatever'
     FOR UPDATE;
      /* do whatever you need to do */
    UPDATE table SET AvailableQuota=AvailableQuota - 10,
                     UsedQuota=UsedQuota + 10
     WHERE ProjectId = 'whatever' AND ResourceNme = 'something'
   COMMIT;

When you use these so-called Locking Reads in a transaction this way, other MySQL clients will wait until you issue your commit operation.

Avoid MyISAM tables for this; they don't support transactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM