- Хитрости PL/SQL Developer или Как мы купили мультиварку — Здесь ничего не написано — ЖЖ
- ноя. 26, 2013
- 10:23 am — Хитрости PL/SQL Developer или Как мы купили мультиварку
- Профилирование PL/SQL кода при помощи IDE PL/SQL Developer
- Проблематика и назначение:
- Методы решения проблемы:
- Метод(процедура) для профилирования:
- Профилирование через IDE PL/SQL Developer:
- Oracle® SQL Developer
- Alphabetic List of SQLcl Commands
- List of Unsupported Commands and Features in SQL*Plus
- Starting and Leaving SQLcl
- Starting Up and Shutting Down a Database
- Entering and Executing Commands
- Manipulating SQL, SQLcl, and PL/SQL Commands
- Formatting Query Results
- Accessing Databases
- Miscellaneous Commands
- Documentation Accessibility
Хитрости PL/SQL Developer или Как мы купили мультиварку — Здесь ничего не написано — ЖЖ
ноя. 26, 2013
10:23 am — Хитрости PL/SQL Developer или Как мы купили мультиварку
Начнём с мультиварки.
Пару недель назад мы приобрели девайс, такой же, как на картинке, Redmond RMC-01. Специально выбрали маленькую модель, всего два литра. Пользуемся каждый день, варим кашу для малыша, для себя суп, рис и компот, пару раз испекли бисквит. По-моему, весьма удобно, тем более, что стоит эта машинка меньше двух тысяч. Не надо заботиться ни о пригорании, ни о том, что суп/каша сбежит, не надо мыть плиту, пар при готовке не валит, вытяжку можно не включать. Чаша съёмная, хорошо отмывается в посудомойке. К мультиварке прилагается книга из 160 рецептов, пока что все опробованные рецепты оказались вполне рабочими.
Прочёл вот эту статью на Хабрахабре, со статьёй я в целом согласен, однако самое интересное там в комментариях. Есть такой «синдром посудомоечной машины», вы все знаете, что стоит произнести слово «посудомойка», и у некоторых слушателей тут же разыгрывается неиллюзорный баттхёрт и они начинают яростно утверждать, что им гораздо легче и удобнее мыть посуду руками, хотя никто особо не спрашивает. Так вот в каментах под мультиваркой всё то же самое, только пуканы возгораются ещё жарче. Тут же обнаружились любители стоять у плиты и помешивать кашу, типа так гораздо проще. Каждый второй почему-то норовит упомянуть, что умеет готовить плов гораздо лучше любой мультиварки, хотя про плов вообще речи не было. Мультиварка — это просто кастрюлька с приделанной к ней конфоркой, никаких чудес в ней нет. А плов, если уж так посмотреть — это такое «авторское» блюдо, которое каждый готовит по-своему, в нём не найти усреднённого, подходящего всем рецепта. Ясное дело, что мультиварка не сможет отразить ваш богатый внутренний мир, однако с варкой всяких утилитарных каш, супчиков и компотов она прекрасно справляется. В большинстве повседневных случаев остаточно накидать продуктов, налить воды и нажать несколько кнопок, дальше о готовке можно забыть до сигнала. Практически тот самый «горшочек, вари» о котором мы когда-то читали в сказках, только с защитой от переполнения. Как верно заметил кто-то в комментариях, «даже если выпустят ковёр-самолёт или скатерть-самобранку, их будут покупать далеко не все».
Также стоит отметить, что некоторое время назад наш начальник отдела принёс в офис четырёхлитровую мультиварку, и всякий желающий может ей пользоваться. Достаточно продвинутых для этого сотрудников в нашем отделе двое, у меня есть шанс стать третьим. Если я принесу на работу пачку геркулеса, то в любое время рабочего дня смогу сварить себе хоть четыре литра свежей каши, и не надо будет носить еду из дома.
Тут мне ещё пришло в голову, что следовало бы чаще читать Хабр, ведь так я смогу отслеживать все технические новинки и гаджеты, буду в курсе всех современных течений и сумею держаться на самом острие прогресса. Прочитал с десяток постов, и понял, что я ничего не понял. И не то, чтобы мне что-то было неясно в деталях — я даже не смог разобрать, о чём идет речь. Короче, я лошара стопроцентный.
Теперь настало время рассказать о некоторых любопытных мелочах в PL/SQL Developer. Уверен, что вы все часто используете PL/SQL Developer как в работе, так и в повседневной жизни. У меня стоит версия 10.0.5.1710. Мини-опрос разработчиков нашего отдела показал, что об этих возможностях никто не знает.
1. Создание пользовательских папок. В дереве объектов, там где в отдельных веточках перечислены пакеты, таблицы, вьюшки и всё остальное, можно создавать пользовательские папки, то есть веточки дерева, содержащие произвольный набор объектов. Для этого тыкаем в самую правую в ряду маленьких кнопочек в cамом верху вкладки «Objects». Появляется окошко создания папки. Справа вверху «Создать новую папку». Для папки указываем название и параметры подключения. Последние нужны для того, чтобы пользовательская папка появлялась в браузере объектов только для этого подключения. Если их не указать, папка будет появляться всегда, при работе с разными проектами довольно неудобно. Папка может быть вложенной по отношению к существующим, для этого указываем Parent. Сам набор объектов для папки можно задать тут же с помощью условия, например object_name like ‘MY%’. Или можно создать пустую папку, а потом на любом объекте в дереве или в тексте кода правой кнопкой — Add to folder.
Очень удобно, если часть объектов схемы относится к предметной области, а часть — к фреймворку. Я, например, выделил в отдельную папку свои пакеты, и отделил таблицы с загружаемыми данными от таблиц с данными расчётов.
2. Встроенный файловый менеджер. Рядом с закладкой Object есть ещё закладка Files. Если предполагается работа с какими-нибудь патчами, выпускаемыми в виде набора файлов, то очень удобно затащить всю папку прямо в эту закладочку и открывать скрипты прямо отсюда, без использования внешнего файлового менеджера. Если у файла нестандартное расширение, то в контекстном меню по правой кнопке есть выбор Open As — Program Window/SQL Window/Command Window.
3. Встроенный генератор данных. Если надо заполнить пустую таблицу какими-нибудь данными для тестировании или демонстрации и неохота возиться со скриптом, то в PL/SQL Developer есть генератор данных. В меню Tools — Data Generator. Вверху выбираем схему и название таблицы, если она создана, либо можно создать произвольную таблицу прямо тут. Затем нажимает кнопочку с многоточием в поле Data и появляется окошко с вариантами заполнения полей. Там есть три закладки: Datasets, Functions, Characters. Наиболее интересна тут вторая закладка — Functions. Можно заполнять поля последовательностью, случайными числами, величинами из фиксированного списка, длинными текстовыми фрагментами, и самое важное — значениями из подзапроса, то есть можно заполнить поле, представляющее собой внешний ключ. Для выбора способа заполнения кликаем на нём два раза. Кроме того, если вы одновременно заполняете с помощью Data Generator несколько связанных таблиц, то в списке полей таблицы есть самый правый столбец Master. Родительская таблица к этому времени уже должна быть вынесена в Data Generator.
Результаты заполнения можно получить в виде SQL-скрипта (средняя из трёх жёлтых кнопок в нижнем левом углу окна).
Если попытаться с помощью Data Generator вставить очень много записей, то выходит очень долго. Скорее, он пригодится, если надо наскоро заполнить таблицу с большим количеством разнородных полей, это будет быстрее, чем писать руками скрипт для всех полей.
4. Макросы. Макросами мало кто пользуется, потому что их почему-то воспринимают, как расширение команды Paste. На самом деле макрос не только вставляет фрагмент текста, он исполняет последовательность операций, выполненных на клавиатуре. То есть можно, поставив макрос на запись, набрать to_date(»,’dd.mm.yyyy’) и клавишами перевести курсор в первые пустые кавычки. При исполнении макроса курсор сам встанет в кавычки, удобнее будет вводить дату. Ещё интереснее макросом исполнять запрос в новом окне. Ставим макрос на запись, затем Alt-N — в открывшейся менюшке клавишами выбираем SQL Window — в новом окне вводим текст запроса — F8. При исполнении макрос будет открывать новое окошко и исполнять в нём запрос.
5. Совсем простая вещь — нажав Ctrl-E, можно просмотреть список последних выполненных SQL-запросов, причём не только за последний запуск PL/SQL Developer, но и за предыдущие.
6. И самое поразительное — оказывается, из PL/SQL Developer можно запускать PL/SQL Developer. Для этого в меню File — New Instance.
Профилирование PL/SQL кода при помощи IDE PL/SQL Developer
Проблематика и назначение:
Периодически Oracle разработчики сталкиваются с проблемой производительности PL/SQL кода. Возникают проблемы с тем, чтобы найти место pl/sql кода, в котором возникают проблемы.
Обычно профилирование pl/sql кода используется, когда необходимо определить проблему производительности в очень большом методе, либо когда у метода много внутренних зависимостей с большим количеством логики, а также нет понимание в каком месте метод код тормозит.
Методы решения проблемы:
В решение проблем с производительность в БД Oracle нам помогут:
- PL/SQL Developer — Популярное IDE для Oracle разработчиков.
- DBMS_PROFILE — Oracle пакет для профилирования (не будет рассматриваться в рамках данной статьи, т.к. информации достаточно на просторах интернета).
Метод(процедура) для профилирования:
В рамках данной статьи покажу всего лишь подход к профилированию, поэтому метод, который мы будем профилировать будет не большим.
Создадим метод для профилирования:
Профилирование через IDE PL/SQL Developer:
В pl/sql Developer запускаем Test Window:
Рисунок 1 — Запуск Test Window
В тестовом окне наберём код для запуска метода check_cycle_performance, заполним входную переменную l_cycle_size и нажмем кнопку для запуска профилирования:
Рисунок 2 — Запуск профилирования в PL/SQL Developer
После запуска выйдет диалоговое окно, которое предложит создать таблицу для профайлера, соглашаемся.
Далее по F8 запускаем метод, после его выполнения переходим во вкладку Profiler:
Рисунок 3 — Окно профайлера в PL/SQL.
Из рисунка 3 видно, что основная проблема по производительности состоит в строке 16.
Не трудно понять, что основная проблема производительности кроется в переключениях контекста SQL — PL/SQL.
При этом возведение в степень: строка 11, занимает гораздо меньше времени.
По мерам предотвращения переключения контекстов рассмотрим в рамках другой статьи.
Oracle® SQL Developer
Command-Line Quick Reference
This Quick Reference discusses the following features of SQL Developer Command-Line (SQLcl):
Alphabetic List of SQLcl Commands
ACC[EPT] variable [NUM[BER] | CHAR | DATE | BINARY_FLOAT | BINARY_DOUBLE] [FOR[MAT] format ] [DEF[AULT] default ] [PROMPT text | NOPR[OMPT ]] [HIDE]
ALIAS [ name >= SQL statement >;| LOAD [ filename >]|SAVE [ filename >] | LIST [ NAME >] | DROP name > | DESC name > Description String >]
ARCHIVE LOG LIST
BRE[AK] [ON report_element [ action [ action ]]] .
BTI[TLE] [ printspec [ text | variable ] . ] | [ON | OFF ]
C[HANGE] sepchar old [ sepchar [ new [ sepchar ]]]
CTAS table new_table
DDL [ object_name [ type ] [SAVE filename ]]
DEF[INE] [ variable ] | [ variable = text ]
DEL [ n | n m | n * | n LAST | * | * n | * LAST | LAST]
ED[IT] [ file_name [. ext ]]
FORMAT [BUFFER | RULES | FILE ]
GET [FILE] file_name [. ext ] [ LIST | NOLIST]
HISTORY [index | FULL | USAGE | SCRIPT | TIME | CLEAR (SESSION)?]
L[IST] [ n | n m | n * | n LAST | * | * n | * LAST | LAST]
LOAD [ schema. ] table_name [ @db_link ] file_name
OERR facility > error >
REPEAT iterations > sleep >
REST [ export [ | ] | modules | privileges | schemas ]
SAV[E] [FILE] file_name [. ext ] [ CRE[ATE ] | REP[LACE] | APP[END]]
SCRIPT script file >
SET system_variable value
SHUTDOWN [ABORT | IMMEDIATE | NORMAL | TRANSACTIONAL [LOCAL]]
SPO[OL] [ filename [. ext ] [CRE[ATE] | REP[LACE] | APP[END]] | OFF | OUT]
SSHTUNNEL username >@ hostname > -i identity_file > [-L localPort:Remotehost:RemotePort]
STARTUP db_options | cdb_options | upgrade_options
STORE
TTI[TLE] [ printspec [ text | variable ] . ] | [ON | OFF ]
You can use the up and down arrow keys to cycle through the previous 100 statements or scripts.
List of Unsupported Commands and Features in SQL*Plus
The TIMING command is replaced by the SET TIMING command.
System Variables and Environment Settings through the SET Command
Starting and Leaving SQLcl
Use the following commands to log in to and out of SQLcl.
SQLCL [[ option ] [ logon | / NOLOG] [ start ]]
where option has the following syntax:
-H[ELP] | -V[ERSION] | [ [-C[OMPATIBILITY] x . y [. z ]]] [-L[OGON]] [-NOLOGINTIME] [-R[ESTRICT] <1 | 2 3>] [-S[ILENT]] [-AC]]
where logon has the following syntax:
and where start has the following syntax:
Commits or rolls back all pending changes, logs out of Oracle, terminates SQLcl and returns control to the operating system.
Commits or rolls back all pending changes, logs out of Oracle, terminates SQLcl and returns control to the operating system.
Starting Up and Shutting Down a Database
Starting up and shutting down a database requires DBA privileges.
STARTUP db_options | cdb_options | upgrade_options
where db options has the following syntax:
[FORCE] [RESTRICT] [PFILE= filename ] [QUIET] [ MOUNT [ dbname ] | [ OPEN [ open_db_options ] [ dbname ] ] | NOMOUNT ]
where open_db_options has the following syntax:
where cdb_options has the following syntax:
where root_connection_options has the following syntax:
PLUGGABLE DATABASE pdbname [FORCE] | [RESTRICT] [ OPEN < open_pdb_options >]
where pdb_connection_options has the following syntax:
where open_pdb_options has the following syntax:
READ WRITE | READ ONLY
and where upgrade_options has the following syntax:
Starts an Oracle Database instance with several options, including mounting and opening a database.
SHUTDOWN [ABORT | IMMEDIATE | NORMAL | TRANSACTIONAL [LOCAL]]
Shuts down a currently running Oracle instance, optionally closing and dismounting a database.
Entering and Executing Commands
Use the following commands to execute and collect timing statistics on SQL commands and PL/SQL blocks:
Executes the most recently executed SQL command or PL/SQL block which is stored in the SQL buffer. Does not list the command. Use slash (/) at the command prompt or line number prompt in SQLcl command line.
Executes a single PL/SQL statement or runs a stored procedure.
Lists and executes the most recently executed SQLcl command or PL/SQL block which is stored in the SQL buffer. The buffer has no command history list and does not record SQLcl commands.
Timing is only available as a switch.
Use the following command to access the help system:
Accesses the command-line help system. Enter HELP INDEX or ? INDEX for a list of topics. You can view the Oracle Database Library at http://www.oracle.com/technology/documentation .
Use the following command to execute operating system commands:
Executes an operating system command without leaving SQLcl. Enter HOST without command to display an operating system prompt. You can then enter multiple operating system commands.
With some operating systems, you can use another character instead of HOST such as «!» (UNIX) and «$» (Windows). See the Oracle installation and user’s manuals provided for your operating system for details.
Use the following command to recall the history of SQLcl commands:
HISTORY [ index | FULL | USAGE | SCRIPT | TIME | CLEAR (SESSION)?] | FAILS
Use the Up and Down arrow keys to navigate through history items at the prompt.
Use the HISTORY command to print the history contents.
History is limited to the last 100 statements.
SET HISTORY LIMIT N allows you to change the default limit, where N is the maximum number.
History is retained between SQLcl sessions.
By default, the SHOW, HISTORY, CONNECT, and SET commands are not saved in history.
SET HISTORY BLACKLIST allows you to set the commands that should not be recorded in history.
Manipulating SQL, SQLcl, and PL/SQL Commands
Use the following commands to edit SQL commands and PL/SQL blocks:
Adds specified text to the end of the current line in the SQL buffer. To separate text from the preceding characters with a space, enter two spaces. To append text that ends with a semicolon, end the command with two semicolons (a single semicolon is interpreted as a command terminator).
C[HANGE] sepchar old [ sepchar [ new [ sepchar ]]]
Changes first occurrence of old on the current line of the SQL buffer. The buffer has no command history list and does not record SQLcl commands. You can use any non-alphanumeric character such as «/» or «!» as a sepchar . You can omit the space between CHANGE and the first sepchar .
DEL [ n | n m | n * | n LAST | * | * n | * LAST | LAST]
Deletes one or more lines of the SQL buffer («*» indicates the current line). You can omit the space between DEL and n or *, but not between DEL and LAST. Enter DEL with no clauses to delete the current line of the buffer. The buffer has no command history list and does not record SQLcl commands.
Adds one or more new lines of text after the current line in the SQL buffer. The buffer has no command history list and does not record SQLcl commands.
L[IST] [ n | n m | n * | n LAST | * | * n | * LAST | LAST]
Lists one or more lines of the most recently executed SQL command or PL/SQL block which is stored in the SQL buffer. Asterisk (*) indicates the current line. You can omit the space between LIST and n or *, but not between LIST and LAST. Enter LIST with no clauses to list all lines.
In SQLcl, you can also use «;» to list all the lines in the SQL buffer. The buffer has no command history list and does not record SQLcl commands.
Use the following commands to run scripts:
Runs the SQLcl statements in the specified script. The script can be called from the local file system or a web server. You can pass values to script variables in the usual way.
Runs the SQLcl statements in the specified script. This command is almost identical to the @ command. It is useful for running nested scripts because it has the additional functionality of looking for the specified script in the same path or url as the calling script.
REPEAT iterations > sleep >
Repeats the current SQL in the buffer at the specified times with sleep intervals. The maximum sleep interval is 120 seconds.
SCRIPT script file >
Runs the SQLcl statements in the specified script.
Runs the SQLcl statements in the specified script. The script can be called from the local file system or a web server. You can pass values to script variables in the usual way.
Use the following commands to create and modify scripts:
ED[IT] [ file_name [. ext ]]
Invokes an operating system text editor on the contents of the specified file or on the contents of the SQL buffer. To edit the buffer contents, omit the file name.
The DEFINE variable _EDITOR can be used to set the editor to use. In SQLcl, _EDITOR can be set to any editor that you prefer. Inline will set the editor to be the SQLcl editor. This supports the following shortcuts:
^R — Run the current buffer
^W — Go to top of buffer
^S — Go to bottom of buffer
^A — Go to start of line
^E — Go to end of line
FORMAT BUFFER — formats the script in the SQLcl Buffer
FORMAT RULES filename > — Loads SQLDeveloper Formatter rules file to formatter
FORMAT FILE input_file > output_file >
GET file_name [. ext ] [LIST | NOLIST]
Loads a SQL statement or PL/SQL block from a file into the SQL buffer. The buffer has no command history list and does not record SQLcl commands.
Begins a comment in a script. The REMARK command must appear at the beginning of a line, and the comment ends at the end of the line (a line cannot contain both a comment and a command). SQLcl does not interpret the comment as a command.
SAV[E] [FILE] file_name [. ext ] [ CRE[ATE ] | REP[LACE] | APP[END]]
Saves the contents of the SQL buffer in a script. The buffer has no command history list and does not record SQLcl commands.
STORE
Saves attributes of the current SQLcl environment in a file.
Performs the specified action (exits SQLcl by default) if an operating system error occurs (such as a file writing error).
Performs the specified action (exits SQLcl by default) if a SQL command or PL/SQL block generates an error.
Use the following commands to write interactive commands:
ACC[EPT] variable [NUM[BER] | CHAR | DATE | BINARY_FLOAT | BINARY_DOUBLE] [FOR[MAT] format ] [DEF[AULT] default ] [PROMPT text | NOPR[OMPT ]] [HIDE]
Reads a line of input and stores it in a given substitution variable.
DEF[INE] [ variable ] | [ variable = text ]
Specifies a substitution variable and assigns a CHAR value to it, or lists the value and variable type of a single variable or all variables.
Displays the specified text then waits for the user to press RETURN.
Sends the specified message or a blank line to the user’s screen.
Deletes one or more substitution variables that you defined either explicitly (with the DEFINE command) or implicitly (with a START command argument).
Use the following commands to create and display bind variables:
Displays the current values of bind variables, or lists all bind variables.
Use the following symbols to create substitution variables and parameters for use in scripts:
Specifies a parameter in a script you run using the START command. START substitutes values you list after the script name as follows: the first for &1, the second for &2, and so on.
Indicates a substitution variable in a SQL or SQLcl command. SQLcl substitutes the value of the specified substitution variable for each substitution variable it encounters. If the substitution variable is undefined, SQLcl prompts you for a value each time an «&» variable is found, and the first time an «&&» variable is found.
Terminates a substitution variable followed by a character that would otherwise be part of the variable name.
Formatting Query Results
Use the following commands to format, store and print your query results.
BRE[AK] [ON report_element [ action [ action ]]] .
Specifies where changes occur in a report and the formatting action to perform, such as:
suppressing the display of duplicate values for a given column
skipping a line each time a given column value changes
printing computed figures each time a given column value changes or at the end of the report
Enter BREAK with no clauses to list the current BREAK definition.
Where report_element has the following syntax:
and where action has the following syntax:
[SKI[P] n | [SKI[P]] PAGE] [ NODUP[LICATES ] | DUP[LICATES]]
BTI[TLE] [ printspec [ text | variable ] . ] | [ON | OFF ]
Places and formats a title at the bottom of each report page, or lists the current BTITLE definition. Use one of the following clauses in place of printspec :
Resets or erases the current value or setting for the specified option.
Where option represents one of the following clauses:
Specifies display attributes for a given column, such as:
text for the column heading
alignment for the column heading
format for NUMBER data
wrapping of column data
Also lists the current display attributes for a single column or for all columns.
Where option represents one of the following clauses:
- ALI[AS] alias
- CLE[AR]
- ENTMAP
- FOR[MAT] format
- HEA[DING] text
- JUS[TIFY]
- LIKE
- NEWL[INE]
- NEW_V[ALUE] variable
- NOPRI[NT] | PRI[NT]
- NUL[L] text
- OLD_V[ALUE] variable
- ON | OFF
- WRA[PPED] | WOR[D_WRAPPED] | TRU[NCATED]
Currently only NEW_V[ALUE] variable syntax is supported.
Enter COLUMN [ < column | expr >FORMAT format ] where the format element specifies the display format for the column.
To change the display format of a NUMBER column, use FORMAT followed by one of the elements in the following table:
Displays a comma in the specified position.
Displays a period (decimal point) to separate the integral and fractional parts of a number.
Displays a leading dollar sign.
Displays leading or trailing zeros (0).
Displays a value with the number of digits specified by the number of 9s. Value has a leading space if positive, a leading minus sign if negative. Blanks are displayed for leading zeros. A zero (0) is displayed for a value of zero.
Displays blanks for the integer part of a fixed-point number when the integer part is zero, regardless of zeros in the format model.
Displays the ISO currency symbol in the specified position.
Displays the decimal character to separate the integral and fractional parts of a number.
Displays a value in scientific notation (format must contain exactly four «E»s).
Displays the group separator in the specified positions in the integral part of a number.
Displays the local currency symbol in the specified position.
Displays a trailing minus sign after a negative value. Displays a trailing space after a positive value.
Displays uppercase Roman numerals. Displays lowercase Roman numerals. Value can be an integer between 1 and 3999.
Displays a leading minus or plus sign. Displays a trailing minus or plus sign.
Displays the smallest number of decimal characters possible. The default is TM9. Fixed notation is used for output up to 64 characters, scientific notation for more than 64 characters. Cannot precede TM with any other element. TM can only be followed by a single 9 or E.
Displays the dual currency symbol in the specified position.
In combination with the BREAK command, calculates and prints summary lines using various standard computations. It also lists all COMPUTE definitions. The following table lists valid functions. All functions except NUMBER apply to non-null values only. COMPUTE functions are always executed in the following sequence AVG, COUNT, MINIMUM, MAXIMUM, NUMBER, SUM, STD, VARIANCE.
Function | Computes | Applies to Datatypes |
---|---|---|
AVG |