Thứ Ba, 8 tháng 7, 2014

[Oracle] Sử dụng kỹ thuật Flashback để phục hồi dữ liệu

Bài tut hướng dẫn dùng kỹ thuật flashback, tối về thử ^^
http://kythuatlaptrinh.com/noi-dung/restore-to-the-points-trong-oracle-10g.html

Bổ sung:
sau khi restore lại database tại 1 restore point nào đó, thì để open lại database cần ở chế độ RESETLOGS hoặc NORESETLOGS:
SQL> alter database open resetlogs;

Thứ Tư, 2 tháng 7, 2014

[Linux] Hướng dẫn sử dụng vi editor căn bản

Trình soạn thảo văn bản khá phổ biến trong Unix. Có một chút kiến thức về vi có thể giúp bạn trong khá nhiều khi làm việc với unix.
Mình có tham khảo web site này hướng dẫn khá chi tiết về cách sử dụng vi editor : http://www.washington.edu/computing/unix/vi.html

Trích dẫn :
-------------------------------------------------------

Entering Text

In order to begin entering text in this empty file, you must change from command mode to insert mode. To do this, type
      i
Nothing appears to change, but you are now in insert mode and can begin typing text. In general, vi's commands do not display on the screen and do not require the Return key to be pressed.
Type a few short lines and press <Return> at the end of each line. If you type a long line, you will notice the vi does not word wrap, it merely breaks the line unceremoniously at the edge of the screen.
If you make a mistake, pressing <Backspace> or <Delete> may remove the error, depending on your terminal type.

Moving the Cursor

To move the cursor to another position, you must be in command mode. If you have just finished typing text, you are still in insert mode. Go back to command mode by pressing <Esc>. If you are not sure which mode you are in, press <Esc> once or twice until you hear a beep. When you hear the beep, you are in command mode.
The cursor is controlled with four keys: h, j, k, l.
     Key        Cursor Movement
     ---        ---------------
     h        left one space
     j        down one line
     k        up one line
     l        right one space
When you have gone as far as possible in one direction, the cursor stops moving and you hear a beep. For example, you cannot use l to move right and wrap around to the next line, you must use j to move down a line. See the section entitled "Moving Around in a File" for ways to move more quickly through a file.

Basic Editing

Editing commands require that you be command mode. Many of the editing commands have a different function depending on whether they are typed as upper- or lowercase. Often, editing commands can be preceded by a number to indicate a repetition of the command.

Deleting Characters

To delete a character from a file, move the cursor until it is on the incorrect letter, then type
      x
The character under the cursor disappears. To remove four characters (the one under the cursor and the next three) type
     4x
To delete the character before the cursor, type
      X (uppercase)

Deleting Words

To delete a word, move the cursor to the first letter of the word, and type
      dw
This command deletes the word and the space following it.
To delete three words type
       3dw

Deleting Lines

To delete a whole line, type
       dd
The cursor does not have to be at the beginning of the line. Typing dd deletes the entire line containing the cursor and places the cursor at the start of the next line. To delete two lines, type
       2dd
To delete from the cursor position to the end of the line, type
       D (uppercase)

Replacing Characters

To replace one character with another:
  1. Move the cursor to the character to be replaced.
  2. Type r
  3. Type the replacement character.
The new character will appear, and you will still be in command mode.

Replacing Words

To replace one word with another, move to the start of the incorrect word and type
     cw
The last letter of the word to be replaced will turn into a $. You are now in insert mode and may type the replacement. The new text does not need to be the same length as the original. Press <Esc> to get back to command mode. To replace three words, type
     3cw

Replacing Lines

To change text from the cursor position to the end of the line:
  1. Type C (uppercase).
  2. Type the replacement text.
  3. Press <Esc>.

Inserting Text

To insert text in a line:
  1. Position the cursor where the new text should go.
  2. Type i
  3. Enter the new text.
The text is inserted BEFORE the cursor.
4. Press <Esc> to get back to command mode.

Appending Text

To add text to the end of a line:
  1. Position the cursor on the last letter of the line.
  2. Type a
  3. Enter the new text.
This adds text AFTER the cursor.
4. Press <Esc> to get back to command mode.

Opening a Blank Line

To insert a blank line below the current line, type
     o (lowercase)
      
To insert a blank line above the current line, type
     O (uppercase)

Joining Lines

To join two lines together:
  1. Put the cursor on the first line to be joined.
  2. Type J
To join three lines together:
  1. Put the cursor on the first line to be joined.
  2. Type 3J

Undoing

To undo your most recent edit, type
     u
To undo all the edits on a single line, type
     U (uppercase)
Undoing all edits on a single line only works as long as the cursor stays on that line. Once you move the cursor off a line, you cannot use U to restore the line.

Moving Around in a File

There are shortcuts to move more quickly though a file. All these work in command mode.
     Key            Movement
     ---            --------
     w            forward word by word
     b            backward word by word
     $            to end of line
     0 (zero)     to beginning of line
     H            to top line of screen
     M            to middle line of screen
     L            to last line of screen
     G            to last line of file
     1G           to first line of file
     <Control>f   scroll forward one screen
     <Control>b   scroll backward one screen
     <Control>d   scroll down one-half screen
     <Control>u   scroll up one-half screen

Moving by Searching

To move quickly by searching for text, while in command mode:
  1. Type / (slash).
  2. Enter the text to search for.
  3. Press <Return>.
The cursor moves to the first occurrence of that text.
To repeat the search in a forward direction, type
     n
To repeat the search in a backward direction, type
     N

Closing and Saving a File

With vi, you edit a copy of the file, rather than the original file. Changes are made to the original only when you save your edits.
To save the file and quit vi, type
     ZZ
The vi editor editor is built on an earler Unix text editor called ex. ex commands can be used within vi. ex commands begin with a : (colon) and end with a <Return>. The command is displayed on the status line as you type. Some ex commands are useful when saving and closing files.
To save the edits you have made, but leave vi running and your file open:
  1. Press <Esc>.
  2. Type :w
  3. Press <Return>.
To quit vi, and discard any changes your have made since last saving:
  1. Press <Esc>.
  2. Type :q!
  3. Press <Return>.

Command Summary

STARTING vi
     vi filename    edit a file named "filename"
     vi newfile     create a new file named "newfile"
ENTERING TEXT
     i            insert text left of cursor
     a            append text right of cursor
MOVING THE CURSOR
     h            left one space
     j            down one line
     k            up one line
     l            right one space
BASIC EDITING
     x         delete character
     nx        delete n characters
     X         delete character before cursor
     dw        delete word
     ndw       delete n words
     dd        delete line
     ndd       delete n lines
     D         delete characters from cursor to end of line
     r         replace character under cursor
     cw        replace a word
     ncw       replace n words
     C         change text from cursor to end of line
     o         insert blank line below cursor
                  (ready for insertion)
     O         insert blank line above cursor
                  (ready for insertion)
     J         join succeeding line to current cursor line
     nJ        join n succeeding lines to current cursor line
     u         undo last change
     U         restore current line
MOVING AROUND IN A FILE
     w            forward word by word
     b            backward word by word
     $            to end of line
     0 (zero)     to beginning of line
     H            to top line of screen
     M            to middle line of screen
     L            to last line of screen
     G            to last line of file
     1G           to first line of file
     <Control>f   scroll forward one screen
     <Control>b   scroll backward one screen
     <Control>d   scroll down one-half screen
     <Control>u   scroll up one-half screen
     n            repeat last search in same direction
     N            repeat last search in opposite direction
CLOSING AND SAVING A FILE
     ZZ            save file and then quit
     :w            save file
     :q!            discard changes and quit file

Thứ Ba, 1 tháng 7, 2014

[Oracle cơ bản] Database Instance

Nội dung:
  • Giới thiệu Database Control, Enterprise Manger.
  • Tham số cấu hình hệ thống Initialization Parameters
  • Các trạng thái của database khi startup.
  • Các lựa chọn khi shutdown database.
  • Đề cập Alert log và Trace files.
  • Giới thiệu Dynamic performance views.
I - Giới thiệu Database Control, Enterprise Manger
Oracle Database cung cấp một giao diện quản lý độc lập (stand-alone management console) database gọi là Database Control. Mỗi database control chỉ quản lý 1 database duy nhất. Enterprise manager là một Web-based database control. Các câu lệnh liên quan đến enterprise manager
emctl status dbconsole
emctl start dbconsole
emctl stop dbconsole
Chú ý, để sử dụng những câu lệnh này, cần set biến môi trường, ở ví dụ của mình là "orcl"

Khi start enterprise manager lên, ta có thể truy cập vào giao diện web để xem. Đường dẫn có dạng
https://ip_server:port/em
Trong đó:
- ip_server là ip của server database
- port kết nối, mặc định là 1158 (nhớ mở kết nối iptables cho port này). Có thể cấu hình lại port này trong file $ORACLE_HOME/install/portlist.ini

II - Initialization Parameter Files
Initialization parameter file là file chứa những tham số cấu hình cho database. Những file dạng này sẽ được đọc khi start instance.

1. Phân biệt hai loại file cấu hình
  1. Server parameter file (SPFILE): Dạng file binary được đọc và ghi bởi server, chúng ta đừng nên đụng vào file này vì là dạng binary nên có đụng vào cũng không hiểu được ^^. SPFILE nằm trên server. Tên mặc định của file này có dạng "spfile<SID>.ora".
  2. Text initialization parameter file (PFILE): Dạng file này có thể được đọc bởi server, nhưng server không thể ghi được. PFILE là dạng text nên người thường có thể đọc được bằng mắt. PFILE vừa nằm trong server, vừa phải có 1 bản copy trên client. Dạng file "init<SID>.ora"
Tăng giá trị cho các tham số parameters có thể găng performance của hệ thống, tuy nhiên đòi hỏi tăng kích thước SGA.

Oracle tìm kiếm parameter file theo thứ tự
  1. Tìm file spfile<SID>.ora trong $ORACLE_HOME/dbs.
  2. Tìm file spfile.ora trong $ORACLE_HOME/dbs.
  3. Tìm file init<SID>.ora trong $ORACLE_HOME/dbs.
2. Phân biệt hai dạng của Initialization Parameter File
Có 2 dạng: basic và advance
Oracle khuyên rằng, trong phần lớn các trường hợp ta chỉ cần sửa 30 basic parameters để tăng performance cho database.
Một số ví dụ về basic parameters:
  • DB_NAME và DB_DOMAIN để xác định tên global của database.
  • Kích thước tổng cộng của SGA: SGA_TARGET.
Một số ví dụ về Initialization Parameters File
  • CONTROL_FILES: chỉ định số lượng control filenames cho database. Oracle đề nghị ít nhất có 2 control file cho mỗi database.
  • DB_FILES: chỉ định tối đa bao nhiêu database files được opened cho 1 database. Giá trị mặc định : 200.
  • PROCESSES: giới hạn số lượng tối đa user processes có thể đồng thời kết nối đến Oracle server. Giá trị mặc định: 100.
  • DB_BLOCK_SIZE: xác định kích thước (bytes) của 1 Oracle database block.
  • DB_CACHE_SIZE: xác định kích thước chuẩn của block buffer cache.
SGA_TARGET
Xác định tổng kích thước vùng SGA, bao gồm các thành phần con bên trong nó. Nếu cấu hình cho SGA_TARGET, thì vùng nhớ của các thành phần con bên trong cũng được tự động cấu hình theo, bao gồm:
  • Buffer cache (DB_CACHE_SIZE).
  • Shared pool (SHARED_POOL_SIZE).
  • Large pool (LARGE_POOL_SIZE).
  • Java pool (JAVA_POOL_SIZE).
  • Streams pool (STREAMS_POOL_SIZE).
3. Thay đổi giá trị trong Initialization Paramter
Chia làm 2 loại tham số: static parameters và dynamic parameters
1. Static parameters: Thay đổi static paramters đòi hỏi phải restart lại database để thay đổi có hiệu lực.
2. Dynamic parameters: Có thể thay đổi được ngay khi database đang chạy. Chia làm 2 loại
- Session-level parameters: chỉ ảnh hưởng trong 1 user session. Sẽ hết tác dụng khi kết thúc user session đó.
- System-level parameters: ảnh hưởng đến toàn bộ database và các session khác trong hệ thống.

4. Tầm vực giá trị trong Initialization Paramter
Giá trị tham số SCOPE áp dụng khi thay đổi static hay dynamic parameters:
  • SCOPE=SPFILE: chỉ thay đổi trên SPFILE. Và chỉ có hiệu lực lần startup tiếp theo của database. Chỉ áp dụng cho static parameters.
  • SCOPE=MEMORY: thay đổi áp dụng trên memory. Có hiệu lực ngay lập tức. Không áp dụng cho static parameters.
  • SCOPE=BOTH: thay đổi áp dụng cả trên SPFILE và memory. Đối với dynamic parameters sẽ có hiệu lực ngay lập tức và ngay cả lần startup tiếp theo của database do đã lưu trên SPFILE. Còn đối với static parameters thì chế độ này không được phép. (Vì static parameters không thể nào có hiệu lực ngay lập tức nên có lưu trên memory cũng vô tác dụng).
Ví dụ
ALTER SESSION SET NLS_DATE_FORMAT = 'mon dd yyyy';
ALTER SYSTEM SET SEC_MAX_FAILED_LOGIN_ATTEMPTS=2 COMMENT='Reduce from 10 for tighter security.' SCOPE=SPFILE;

III - Các trạng thái của database khi startup
Khi start database instance, có nhiều trạng thái để lựa chọn vị trí bắt đầu start: NOMOUNT, MOUNT, OPEN.

1. Chế độ NOMOUNT
Các công việc thực hiện trong chế độ NOMOUNT:
  • Tìm kiếm initialization parameter file theo thứ tự: kiếm spfile<SID>.ora đầu tiên, nếu không có kiếm spfile.ora, nếu không có nữa thì kiếm init<SID>.ora.
  • Cấp phát vùng nhớ SGA.
  • Start background processes.
  • Mở alert<SID>.log file và trace files.
2. Chế độ MOUNT
Các công việc thực hiện trong chế độ MOUNT:
  • Kế thừa trạng thái database ở chế độ NOMOUNT.
  • Xác định vị trí và open tất cả các control files xác định trong parameter file.
  • Đọc từ control files để lấy ra tên và trạng thái hoạt động của data files và online redo log files. Tuy nhiên, bước này không cần kiểm tra sự tồn tại thực sự của data files và online redo log files.
Một số trường hợp sử dụng chế độ MOUNT nhưng không cần OPEN database:
  • Rename data files.
  • Enable hoặc Disable online redo log file archiving.
  • Performing full database recovery.
3. Chế độ OPEN
Trạng thái hoạt động của database tức là instance được started và datase được mounted và opented để bất kì user hợp lệ nào cũng đều có thể kết nối được đến database.
Các công việc thực hiện trong chế độ OPEN:
  • Open data files
  • Open online redo log files
Trong bước cuối cùng này, Oracle server sẽ kiểm tra tất cả data files và online redo log files phải được opened và kiểm tra luôn tính nhất quán (consistency) của database. Nếu không đảm bảo điều kiện này, Oracle server sẽ văng lỗi trả về.


4. Ví dụ sử dụng sqlplus để start instance
Start instance, sau đó mount và open database
SQL> startup
Start instance và database ở chế độ NOMOUNT
SQL> startup nomount
Lệnh mount database từ trạng thái NOMOUNT
SQL> alter database mount;
Lệnh open database từ trạng thái MOUNT
SQL> alter database open;

Ngoài ra, khi cài đặt Oracle Restart, có thể sử dụng srvctl utility để start database instance. Ưu điểm khi dùng srvctl utility là nó có thể start tất cả các resource khác như ASM instance, ASM disk groups và listener.

IV - Các lựa chọn khi shutdown database
Có 4 chế độ shutdown:
  1. NORMAL: chờ đến khi tất cả session disconnect, là loại shutdown chậm nhất.
  2. TRANSACTIONAL: cho phép những transaction hiện tại kết thúc, nhưng không cho phép tạo mới transaction nữa.
  3. IMMEDIATE: loại thường được sử dụng nhất. Những transaction nào chưa commit sẽ bị roll back.
  4. ABORT: thực hiện ít công việc nhất có thể trước khi shutdown, là loại shutdown nhanh nhất. Khi sử dụng shutdown ABORT thì lần start tới sẽ đòi hỏi chạy instance recovery.

Quá trình shutdown ở các chế độ: NORMAL, TRANSACTIONAL, IMMEDIATE
1. NORMAL
Là chế độ mặc định (sử dụng SQL*PLUS) khi shutdown nếu không chỉ định cụ thể shutdown ở chế độ nào. NORMAL shutdown chỉ thực hiện trong những điều kiện sau:
  • Không tạo thêm connection mới.
  • Chờ cho tất cả users disconnect.
  • Database và redo buffers được ghi xuống disk.
  • Tắt background processes và thu hồi vùng nhớ của SGA.
  • Oracle server close và dismount database trước khi shutdown instance.
  • Lần start kế tiếp không cần instance recovery.
  • Bảo toàn tính toàn vẹn database.
2. TRANSACTION
Chế độ này đảm bảo dữ liệu của client không bị mất, chờ đến khi transaction của client hoàn thành. Thực hiện trong các điều kiện sau:
  • Không cho tạo mới transaction từ client.
  • Client sẽ bị disconnect khi kết thúc transaction.
  • Khi tất cả các transaction hoàn tất, thực hiện shutdown ngay lập tức.
  • Lần start kế tiếp không cần instance recovery.
  • Bảo toàn tính toàn vẹn database.
3. IMMEDIATE
Là chế độ default khi thực hiện shutdown trong Enterprise Manager.
Thực hiện trong điều kiện:
  • Những câu lệnh SQL nào đang chạy sẽ bị ngắt.
  • Oracle server không chờ user tự disconnect khỏi database.
  • Roll back tất cả transactions và disconnect tất cả users.
  • Close và dismount database trước khi shutdown instance.
  • Lần start kế tiếp không cần instance recovery.
  • Bảo toàn tính toàn vẹn database.
Quá trình shutdown ABORT
4. ABORT
Thực hiện trong các điều kiện:
  • Những câu lệnh SQL nào đang chạy sẽ bị ngắt.
  •  Oracle server không chờ user tự disconnect khỏi database.
  • Database và redo buffers không được ghi xuống disks.
  • Uncommitted transactions không được roll back.
  • Instance sẽ bị tắt mà không đóng lại các files.
  • Database không được closed và dismounted.
  • Lần start tiếp theo yêu cầu chế độ instance recovery. 
  • Không bảo toàn tính toàn vẹn của database.
V - Alert Log và Trace Files
Phần này chủ yếu nói về phần ghi log các tác động đến DB, hay các lỗi phát sinh khi server và background processes chạy.

VI - Dynamic Performace Views
Phần này đề cập 2 khái niệm về Dynamic Performance Views và Data Dictionary Views

1. Dynamic Performance Views
Là những bảng ảo lưu trữ trên memory structure của database, bắt đầu bằng từ khóa "v$", chứa thông tin vận hành và hiệu năng (performance) của database instance.
Dynamic performance views chứa các thông tin gồm:
  • Sessions
  • File states
  • Tiến trình
  • Locks
  • Backup status
  • Cấp phát và sử dụng memory
  • System và session parameters
  • SQL execution
Một số ví dụ về cách sử dụng dynamic performance views:
Lấy ra câu truy vấn nào có thời gian CPU thực hiện trên 200,000 microseconds
SQL> SELECT sql_text, executions FROM v$sql WHERE cpu_time > 200000;
Lấy ra các sessions IDs đang dữ lock
SQL> SELECT sid, ctime FROM v$lock WHERE block > 0;

2. Data Dictionary
Chứa thông tin metadata của database, bao gồm tên và thuộc tính của tất cả các objects trong database. Những thay đổi ảnh hưởng đến bất kì object nào trong database đều được update vào data dictionary.
Data dictionary dùng để:
  • Được Oracle database server dùng để tìm kiếm thông tin users, objects, constraints, lưu trữ.
  • Được vận hành bởi Oracle database server.
  • User có thể truy vấn thông tin về database thông qua các view truy xuất thông tin từ data dictionary.
  • Được sở hữu bởi user SYS.
  • Không nên chỉnh sửa trực tiếp thông qua câu SQL vào những thông tin của data dictionary.
Một số loại view chính trong Data dictionary
- Prefix DBA_ : được xem tất cả thông tin và  một số thông tin chỉ dành cho DBA, chỉ có người dùng có quyền DBA mới xem được.
- Prefix ALL_ : được xem tất cả thông tin objects mà user được cấp quyền xem, bất kể đối objects đó có thuộc sở hữu của user đó hay không.
- Prefix USER_ : có tầm vực nhỏ nhất, chỉ được xem thông tin những objects mà user sở hữu.

Một số ví dụ về truy vấn thông tin trong data dictionary view
Lấy thông tin table_name, tablespace_name trong shema đang sử dụng:
SELECT table_name, tablespace_name FROM user_tables;
Lấy thông tin các user có thể log in vào hệ thống:
SELECT username, account_status FROM dab_users WHERE account_status = 'OPEN';


Link tham khảo: