Oracle 数据隔离级别(Transaction Isolation Levels) 说明

From 11gR2:

http://download.oracle.com/docs/cd/E11882_01/server.112/e16508/consist.htm#CNCPT621

一. ANSI/ISO Transaction Isolation Levels(ANSI/ISO标准的隔离级别)

The SQL standard, which has been adoptedby both ANSI and ISO/IEC, defines four levels of transaction isolation. Theselevels have differing degrees of impact on transaction processing throughput.

Theseisolation levels are defined in terms of phenomena that must be preventedbetween concurrently executing transactions. The preventable phenomena are:

--isolation levels 的一些表现

(1)Dirtyreads(脏读)

Atransaction reads data that has been written by another transaction that hasnot been committed yet.

--一个事务读取另一个事务已经修改但为提交的数据

(2)Nonrepeatable (fuzzy) reads(模糊读)

Atransaction rereads data it has previously read and finds that anothercommitted transaction has modified or deleted the data. For example, a userqueries a row and then later queries the same row, onlyto discover that the data has changed.

--当事务重读之前的数据时,发现这个事务被另一个事务修改,如modified 或者deleted,并且已经提交。

(3)Phantomreads

Atransaction reruns a queryreturning a set of rows that satisfies a search condition and finds thatanother committed transaction has inserted additional rows that satisfy thecondition.

--同一查询在同一事务中多次进行,由于其他提交事务所做的插入操作,每次返回不同的结果集,此时发生幻像读。

Forexample, a transaction queries the number of employees. Five minutes later itperforms the same query, but now the number has increased by one becauseanother user inserted a record for a new hire. More data satisfies the querycriteria than before, but unlike in a fuzzy read thepreviously read data is unchanged.

TheSQL standard defines four levels of isolation in terms of the phenomena that atransaction running at a particular isolation level is permitted to experience.Table9-1 shows the levels.

Table 9-1 Preventable ReadPhenomena by Isolation Level

OracleDatabase offers the read committed (default) andserializable isolation levels. Also, the database offers a read-only mode.

隔离级别与并发性是互为矛盾的:隔离程度越高,数据库的并发性越差;隔离程度越低,数据库的并发性越好。

ANSI/ISO标准定义了一些数据库操作的隔离级别:

(1)未提交读(read uncommitted)

(2)提交读(read committed)

(3)重复读(repeatable read)

(4)序列化(Serializable)

二. Oracle Database Transaction Isolation Levels(Oracle 标准的隔离级别)

Table9-1 summarizes the ANSI standard for transaction isolation levels. Thestandard is defined in terms of the phenomena that are either permitted orprevented for each isolation level. Oracle Databaseprovides the transaction isolation levels:

(1)ReadCommitted Isolation Level

(2)SerializableIsolation Level

(3)Read-OnlyIsolation Level

2.1 Read CommittedIsolation Level

In the read committedisolation level, which is the default, everyquery executed by a transaction sees only data committed before the query—notthe transaction—began. This level of isolation is appropriate for databaseenvironments in which few transactions are likely to conflict.

A query in a read committed transaction avoids reading datathat commits while the query is in progress. For example, if a query ishalfway through a scan of a million-row table, and if a different transactioncommits an update to row 950,000, then the query does not see this change whenit reads row 950,000. However, because the database does not prevent othertransactions from modifying data read by a query, other transactions may changedata between query executions. Thus, a transaction that runs the same querytwice may experience fuzzy reads and phantoms.

2.1.1 ReadConsistency in the Read Committed Isolation Level

A consistent result set is provided forevery query, guaranteeing data consistency, with no action by the user. An implicitquery, such as a query implied by a WHERE clause in an UPDATE statement, isguaranteed a consistent set of results. However, each statement in an implicitquery does not see the changes made by the DML statement itself, but sees thedata as it existed before changes were made.

Ifa SELECT list contains a PL/SQL function, then the database appliesstatement-level read consistency at the statement level for SQL run within thePL/SQL function code, rather than at the parent SQL level. For example, afunction could access a table whose data is changed and committed by anotheruser. For each execution of the SELECT in the function, a new read-consistentsnapshot is established.

See Also:

"Subqueriesand Implicit Queries"

2.1.2 Conflicting Writes in Read CommittedTransactions

Ina read committed transaction, a conflicting write occurs when the transaction attempts tochange a row updated by an uncommitted concurrent transaction, sometimes calleda blocking transaction. The read committed transaction waits for the blockingtransaction to end and release its row lock. The options are as follows:

(1)If the blocking transaction rolls back, then the waiting transactionproceeds to change the previously locked row as if the other transaction neverexisted.

(2)If the blocking transaction commits and releases its locks, then thewaiting transaction proceeds with its intended update to the newly changed row.

Table9-2 shows how transaction 1, which can be either serializable or readcommitted, interacts with read committed transaction 2. Table9-2 shows a classic situation known as a lost update (see "Useof Locks"). The update made by transaction 1 is not in the table eventhough transaction 1 committed it. Devising a strategy to handle lost updatesis an important part of application development.

eg: Conflicting Writes and Lost Updates in a READCOMMITTED Transaction

session 1:

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 6200

Greene 9500

-- Session 1 queries the salaries forBanda, Greene, and Hintz. No employee named Hintz is found.

SQL> UPDATE employees SET salary = 7000WHERE last_name = 'Banda';

--Session 1 begins a transaction by updatingthe Banda salary. The default isolation level for transaction 1 is READCOMMITTED.

Session 2:

SQL> SET TRANSACTION ISOLATION LEVELREAD COMMITTED;

--Session 2 begins transaction 2 and setsthe isolation level explicitly to READ COMMITTED.

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 6200

Greene 9500

--Transaction 2 queries the salaries forBanda, Greene, and Hintz. Oracle Database uses read consistency to show thesalary for Banda before the uncommitted update made by transaction 1.

SQL> UPDATE employees SET salary =9900WHERE last_name = 'Greene';

--Transaction 2 updates the salary forGreene successfully because transaction 1 locked only the Banda row (see "RowLocks (TX)").

Session 1:

SQL> INSERT INTO employees (employee_id,last_name, email,hire_date, job_id) VALUES (210,'Hintz', 'JHINTZ', SYSDATE,'SH_CLERK');

--Transaction 1 inserts a row for employeeHintz, but does not commit.

Session 2:

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda6200

Greene 9900

-- Transaction 2 queries the salaries foremployees Banda, Greene, and Hintz.

Transaction 2 sees its own update to thesalary for Greene. Transaction 2 does not see the uncommitted update to thesalary for Banda or the insertion for Hintz made by transaction 1.

SQL> UPDATE employees SET salary =6300WHERE last_name = 'Banda';

-- prompt does not return

-- Transaction 2 attempts to update the rowfor Banda, which is currently locked by transaction 1, creating a conflictingwrite. Transaction 2 waits until transaction 1 ends.

Session 1:

SQL> COMMIT;

--Transaction 1 commits its work, endingthe transaction.

session 2:

1 row updated.

SQL>

--The lock on the Banda row is nowreleased, so transaction 2 proceeds with its update to the salary for Banda.

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 6300

Greene 9900

Hintz

--Transaction 2 queries the salaries foremployees Banda, Greene, and Hintz. The Hintz insert committed by transaction 1is now visible to transaction 2. Transaction 2 sees its own update to the Bandasalary.

SQL>COMMIT;

--Transaction 2 commits its work, endingthe transaction.

session 1:

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 6300

Greene 9900

Hintz

--Session 1 queries the rows for Banda,Greene, and Hintz. The salary for Banda is 6300, which is the update made bytransaction 2. The update of Banda's salary to 7000 made by transaction 1 isnow "lost."

2.2 Serializable Isolation Level

In the serialization isolation level, atransaction sees only changes committed at the time the transaction—not thequery—began and changes made by the transaction itself. A serializabletransaction operates in an environment that makes it appear as if no otherusers were modifying data in the database.

Serializable isolation issuitable for environments:

(1)With large databases and short transactions that update only a fewrows

(2)Where the chance that two concurrent transactions will modify thesame rows is relatively low

(3)Where relatively long-running transactions are primarily read only

Inserializable isolation, the read consistency normally obtained at the statementlevel extends to the entire transaction. Any row read by the transaction isassured to be the same when reread. Any query isguaranteed to return the same results for the duration of the transaction,so changes made by other transactions are not visible to the query regardlessof how long it has been running. Serializabletransactions do not experience dirty reads, fuzzy reads, or phantom reads.

Oracle Database permits a serializable transaction to modifya row only if changes to the row made by other transactions were alreadycommitted when the serializable transaction began. The databasegenerates an error when a serializable transaction tries to update or deletedata changed by a different transaction that committed after the serializabletransaction began:

ORA-08177:Cannot serialize access for this transaction

When a serializable transaction fails withthe ORA-08177error, an application can take several actions, including the following:

(1)Commit the work executed to that point

(2)Execute additional (but different) statements, perhaps after rollingback to a savepointestablished earlier in the transaction

(3)Roll back the entire transaction

Table9-3 shows how a serializable transaction interacts with other transactions.If the serializable transaction does not try to change a row committed byanother transaction after the serializable transaction began, then a serializedaccess problem is avoided.

Eg: Read Consistency andSerialized Access Problems in Serializable Transactions

Session 1:

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 6200

Greene 9500

--Session 1 queries the salaries for Banda,Greene, and Hintz. No employee named Hintz is found.

SQL> UPDATE employees SET salary = 7000WHERE last_name = 'Banda';

--Session 1 begins transaction 1 byupdating the Banda salary. The default isolation level for is READ COMMITTED.

Session 2:

SQL> SET TRANSACTION ISOLATION LEVELSERIALIZABLE;

--Session 2 begins transaction 2 and setsit to the SERIALIZABLE isolation level.

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 6200

Greene 9500

--Transaction 2 queries the salaries forBanda, Greene, and Hintz. Oracle Database uses read consistency to show thesalary for Banda before the uncommitted update made by transaction 1.

SQL> UPDATE employees SET salary =9900WHERE last_name = 'Greene';

--Transaction 2 updates the Greene salarysuccessfully because only the Banda row is locked.

Session 1:

SQL> INSERT INTO employees (employee_id,last_name, email, hire_date, job_id) VALUES (210,'Hintz', 'JHINTZ', SYSDATE,'SH_CLERK');

-- Transaction 1 inserts a row for employeeHintz.

SQL> COMMIT;

-- Transaction 1 commits its work, endingthe transaction.

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 7000

Greene 9500

Hintz

Session 2:

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 6200

Greene 9900

-- Session 1 queries the salaries foremployees Banda, Greene, and Hintz and sees changes committed by transaction 1.Session 1 does not see the uncommitted Greene update made by transaction 2.

Transaction2 queries the salaries for employees Banda, Greene, and Hintz. Oracle Databaseread consistency ensures that the Hintz insert and Banda update committed bytransaction 1 are not visible to transaction 2. Transaction 2 sees its ownupdate to the Banda salary.

SQL> COMMIT;

--Transaction 2 commits its work, endingthe transaction.

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 7000

Greene 9900

Hintz

Session 1:

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 7000

Greene 9900

Hintz

-- Both sessions query the salaries forBanda, Greene, and Hintz. Each session sees all committed changes made bytransaction 1 and transaction 2.

SQL> UPDATE employees SET salary = 7100WHERE last_name = 'Hintz';

--Session 1 begins transaction 3 byupdating the Hintz salary. The default isolation level for transaction 3 isREAD COMMITTED.

Session 2:

SQL> SET TRANSACTION ISOLATION LEVELSERIALIZABLE;

-- Session 2 begins transaction 4 and sets it to the SERIALIZABLEisolation level.

SQL> UPDATE employees SET salary = 7200WHERE last_name = 'Hintz';

-- prompt does not return

-- Transaction 4 attempts to update thesalary for Hintz, but is blocked because transaction 3 locked the Hintz row(see "RowLocks (TX)"). Transaction 4 queues behind transaction 3.

Session 1:

SQL> COMMIT;

--Transaction 3 commits its update of theHintz salary, ending the transaction.

Session 2:

UPDATE employees SET salary = 7200WHERElast_name = 'Hintz'

*

ERROR at line 1:

ORA-08177: can'tserialize access for this transaction

-- The commit that ends transaction 3 causes the Hintz update intransaction 4 to fail with the ORA-08177 error.The problem error occurs because transaction 3 committed the Hintz update aftertransaction 4 began.

SQL> ROLLBACK;

--Session 2 rolls back transaction 4, whichends the transaction.

SQL> SET TRANSACTION ISOLATION LEVELSERIALIZABLE;

--Session 2 begins transaction 5 and setsit to the SERIALIZABLE isolation level.

SQL> SELECT last_name, salary FROMemployees WHERE last_name IN ('Banda','Greene','Hintz');

LAST_NAME SALARY

------------- ----------

Banda 7100

Greene 9500

Hintz 7100

--Transaction 5 queries the salaries forBanda, Greene, and Hintz. The Hintz salary update committed by transaction 3 isvisible.

SQL> UPDATE employees SET salary =7200WHERE last_name = 'Hintz';

1 row updated.

--Transaction 5 updates the Hintz salary toa different value. Because the Hintz update made by transaction 3 committedbefore the start of transaction 5, the serialized access problem is avoided.

Note: If a different transaction updatedand committed the Hintz row after transaction transaction 5 began, then theserialized access problem would occur again.

SQL> COMMIT;

--Session 2 commits the update without anyproblems, ending the transaction.

See Also:

"Overviewof Transaction Control"

2.3 Read-OnlyIsolation Level

The read-only isolation level is similarto the serializable isolation level, but read-onlytransactions do not permit data to be modified in the transaction unless theuser is SYS. Thus, read-only transactions are not susceptible to the ORA-08177 error. Read-only transactions are useful forgenerating reports in which the contents must be consistent with respect to thetime when the transaction began.

Oracle Database achieves read consistency by reconstructingdata as needed from the undo segments. Because undo segments are used ina circular fashion, the database can overwrite undo data. Long-running reportsrun the risk that undo data required for read consistency may have been reusedby a different transaction, raising a snapshot too old error. Setting an undo retention period, which is the minimumamount of time that the database attempts to retain old undo data beforeoverwriting it, appropriately avoids this problem.

三. Setthe Isolation Level

Applicationdesigners, application developers, and database administrators can chooseappropriate isolation levels for different transactions, depending on theapplication and workload. Youcan set the isolation level of a transaction by using one of these statementsat the beginning of a transaction:

--在事务开始之前设置,否则会报错误:

ORA-01453: SETTRANSACTION must be first statement of transaction

SQL>SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

SQL>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SQL>SET TRANSACTION READ ONLY;

 

Tosave the networking and processing cost of beginning each transaction with aSET TRANSACTION statement, you can use the ALTER SESSIONstatement to set the transaction isolation level for all subsequent transactions:

SQL>ALTER SESSION SET ISOLATION_LEVELSERIALIZABLE;

SQL>ALTER SESSION SET ISOLATION_LEVELREAD COMMITTED;

-------------------------------------------------------------------------------------------------------

Blog: http://blog.youkuaiyun.com/tianlesoftware

Email: dvd.dba@gmail.com

DBA1 群:62697716(满); DBA2 群:62697977(满)DBA3 群:62697850(满)

DBA 超级群:63306533(满); DBA4 群: 83829929 DBA5群: 142216823

DBA6 群:158654907 聊天 群:40132017 聊天2群:69087192

--加群需要在备注说明Oracle表空间和数据文件的关系,否则拒绝申请

<think>好的,用户想做一个微信小程序,主题是愚公移山,每个人每秒钟生成10个子。我需要先理解用户的需求。首先,愚公移山的故事是关于坚持不懈的精神,所以小程序可能希望用户通过不断“生子”来象征移山的努力。 用户提到每秒钟生成10个子,这可能意味着用户需要一种自动增长的机制,但每秒10个的速度非常快,需要考虑实际可行性。微信小程序的性能是否支持这么高的生成频率?可能需要调整速度,比如每秒1个或每分钟几个,以避免卡顿或数据过载。 接下来,用户可能需要功能设计方面的建议。比如用户如何开始生成子嗣,是否需要点击按钮,还是自动进行。界面设计可能需要显示当前子嗣数量、移山进度,以及可能的成就系统来激励用户持续参。 数据存储方面,用户的进度需要保存在本地或服务器。本地存储简单但容易丢失,云开发可以持久化数据但涉及成本。用户可能没有技术背景,需要推荐易用的解决方案,比如微信云开发。 动画效果方面,简单的粒子效果或图标移动可以增强体验,但复杂动画可能影响性能。需要平衡美观和流畅度。 合规性方面,微信小程序有严格的内容规范,确保主题不涉及敏感内容,比如“生子”是否符合规定,可能需要调整用词,比如改为“帮手”或“工人”。 用户可能希望加入社交元素,比如排行榜或分享功能,让朋友之间竞争,增加活跃度。但需要用户授权和隐私保护。 最后,用户可能需要技术实现步骤的指导,比如使用setInterval或WebSocket进行实时更新,前端框架的选择,以及后端如何处理高并发请求。如果用户是新手,可能需要更详细的教程或推荐开发工具。 总结,用户的核心需求是做一个以愚公移山为主题的微信小程序,核心机制是自动生成子嗣来移山。需要从功能设计、技术实现、合规性和用户体验等方面提供建议,同时考虑实际可行性和用户的技术水平,给出合适的解决方案。</think>好的!如果要设计一个以“愚公移山”为主题的微信小程序,核心机制是“每秒钟生成10个子”来模拟愚公家族不断壮大的过程,以下是分步实现的思路和建议: --- ### **一、核心机制设计** 1. **子嗣生成逻辑** - **自动增长**:每秒自动生成10个子嗣(需考虑实际性能,建议用虚拟数值而非实时渲染大量对象)。 - **手动触发**:添加按钮让用户点击加速生成(例如“召集村民帮忙”)。 2. **数值平衡** - **初始速度**:1秒/10个子(默认速率)。 - **加速规则**:通过道具或成就提升速度(如“神话加成”使速度翻倍)。 --- ### **二、技术实现方案** #### **前端(微信小程序框架)** 1. **计时器控制** ```javascript let timer = null; let childrenCount = 0; // 启动生成 function startGenerating() { timer = setInterval(() => { childrenCount += 10; // 每秒+10 this.setData({ count: childrenCount }); }, 1000); } // 停止生成 function stopGenerating() { clearInterval(timer); } ``` 2. **动画效果** - 使用CSS3动画或`<canvas>`绘制简单粒子效果(如小人物图标从底部向上飘动)。 #### **后端(可选)** - 如需保存用户进度,可使用微信云开发(云数据库): ```javascript const db = wx.cloud.database(); // 存储数据 db.collection('users').add({ data: { count: childrenCount, timestamp: new Date() } }); ``` --- ### **三、功能扩展建议** 1. **移山进度可视化** - 设计一个山脉图标,子嗣数量越多,山脉逐渐被“挖空”(通过进度条或图形变化体现)。 2. **成就系统** - 里程碑奖励(如“1000子嗣解锁新工具”)。 - 彩蛋事件(如“玉帝感动,瞬间生成10000子”)。 3. **社交互动** - 排行榜:对比好友的移山进度。 - 分享助力:邀请好友加速生成。 --- ### **四、注意事项** 1. **性能优化** - 避免高频更新UI导致卡顿,可改为每秒更新一次数值。 - 粒子动画需限制最大数量(如仅显示最后100个子嗣的动画)。 2. **合规性** - 避免使用“生子”等敏感词汇,可替换为“帮手”“工人”等。 3. **用户留存** - 加入离线收益(关闭小程序后按时间计算子嗣增长)。 --- ### **五、示例界面设计** 1. **主页布局** ``` [山脉图标(动态减少)] [当前子嗣数量:10000] [加速按钮] [分享按钮] [成就列表] ``` 2. **动效灵感** - 子嗣图标从屏幕底部向上滑动,象征“移山”。 --- 如果需要具体代码片段或更详细的技术实现步骤,可以告诉我您想深入的部分(如动画、云存储等)! 🌄
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值