Что такое sql скрипт
Перейти к содержимому

Что такое sql скрипт

  • автор:

Что такое sql скрипт

SQL-скрипты миграции представляют собой текстовые файлы с набором DDL и DML команд, разделенных символом “^”. Символ “^” применяется для того, чтобы можно было применять разделитель “;” в составе сложных команд, например, при создании функций или триггеров. Механизм исполнения скриптов разделяет входной файл на команды по разделителю “^” и выполняет каждую команду в отдельной транзакции. Это означает, что при необходимости можно сгруппировать несколько простых операторов (например, insert ), разделенных точкой с запятой, и обеспечить их выполнение в одной транзакции.

Разделитель «^» может быть заэкранирован путем его удвоения. Например, если вам нужно передать значение ^[0-9\s]+$ , скрипт должен содержать строку ^^[0-9\s]+$ .

Пример SQL-скрипта обновления:

create table LIBRARY_COUNTRY ( ID varchar(36) not null, CREATE_TS time, CREATED_BY varchar(50), NAME varchar(100) not null, primary key (ID) )^ alter table LIBRARY_TOWN add column COUNTRY_ID varchar(36) ^ alter table LIBRARY_TOWN add constraint FK_LIBRARY_TOWN_COUNTRY_ID foreign key (COUNTRY_ID) references LIBRARY_COUNTRY(ID)^ create index IDX_LIBRARY_TOWN_COUNTRY on LIBRARY_TOWN (COUNTRY_ID)^

2 Using SQL Scripts

This section provides information on how to use SQL Scripts to create, edit, view, run, and delete script files.

This section contains the following topics:

  • What is SQL Scripts?
  • Accessing SQL Scripts
  • Creating a SQL Script
  • Using the Script Editor
  • Deleting a SQL Script
  • Copying a SQL Script
  • Executing a SQL Script
  • Viewing SQL Script Results
  • Exporting and Importing SQL Scripts
  • Viewing Script and Result Quotas

What is SQL Scripts?

A SQL script is a set of SQL commands saved as a file in SQL Scripts. A SQL script can contain one or more SQL statements or PL/SQL blocks. You can use SQL Scripts to create, edit, view, run, and delete script files.

When using SQL Scripts, remember the following:

  • SQL*Plus commands in a SQL script are ignored at run time.
  • There is no interaction between SQL Commands and SQL Scripts.
  • You can cut and paste a SQL command from the SQL Script editor to run it in SQL Commands.
  • SQL Scripts does not support bind variables.

Accessing SQL Scripts

To access SQL Scripts:

  1. Log in to the Workspace home page.
  2. To view SQL Scripts page you can either:
    • Click the SQL Workshop icon and then SQL Scripts to drill-down to the SQL Scripts page.
    • Click the down arrow on the right side of the SQL Workshop icon to view a drop down menu. Then select the SQL Scripts menu option.

    Description of the illustration scripts.gif

For the purposes of consistency, this document uses the primary navigation path (or drill-down approach) when explaining navigation.

About the SQL Scripts Page

The SQL Scripts page display all SQL scripts created by the current user. You can control the appearance of the page by making a selection from the View list. The default view, Icons, displays each script as an icon. Details view displays each script as a row in a report.

The SQL Scripts page features the following controls:

  • Script. Search for a script by entering the script name, or a partial name, in the Script field and clicking Go . You control how many rows display by making a selection from the Display list.
  • Owner. Search for the owner of the script you want to view by entering the user name in the Owner field and clicking Go .
  • View. Change the appearance of the SQL Scripts page by making a selection from the View list and clicking Go . Available View options include:
    • Icons (default) displays each script as an icon identified by the script name. Click the Show Results check box to additionally display run results as icons identified by the script name.
    • Details displays each script as a line in a report. Each line includes a check box to enable the selection of scripts for deletion, an edit icon to enable the script to be loaded into the script editor, the script name, the script owner, when the script was last updated and by who, the size in bytes, the number of times the script has been run linked to the run results, and an icon to enable the script to be run. Details view offers the following additional controls:
      • Delete Checked. In Details view, select the check box associated with the script you want to delete and click Delete Checked . See «Deleting a SQL Script».
      • Sort. In Details view, click a column heading to sort the listed scripts by that column.

      Switching to Another SQL Workshop Component

      You can navigate to another SQL Workshop component by making a selection from the Component list located on the upper right side of the page:

      • Object Browser . See «Managing Database Objects with Object Browser».
      • SQL Commands . See «Using SQL Commands».
      • SQL Scripts . See «Using SQL Scripts».
      • Query Builder . See «Building Queries with Query Builder».

      About the Tasks List

      A Tasks list displays on the right side of the SQL Scripts page.

      The Task list contains the following links:

      • Manage Results enables you to view, search, and display results. See «Viewing SQL Script Results».
      • Show Quotas displays the Script Quotas page. The Script Quotas page shows the maximum size of a single result, the maximum size of all results, the quota used and the quota free. It also shows the maximum size of a SQL Script.
      • Export enables you to export multiple scripts from the current SQL Script Repository for import into SQL Scripts in a different workspace. The scripts you select to export are encoded in a single export script written to your local file system. The export script is named workspace_name _script.sql by default. See «Exporting and Importing SQL Scripts».
      • Import enables you to import a script exported by this workspace, or a different workspace. Import only imports scripts encoded in an export script created using Export . The export script to import must be accessible on your local file system. See «Exporting and Importing SQL Scripts».

      Creating a SQL Script

      You can create a script in the Script Repository by:

      • Creating a script in the Script Editor
      • Uploading a script from your local file system

      Topics in this section include:

      • Creating a SQL Script in the Script Editor
      • Uploading a SQL Script

      Creating a SQL Script in the Script Editor

      To create an SQL script in the Script Editor:

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. Click the Create button. The Script Editor appears.
      3. Enter a name for the script in the Script Name field. Script name extensions are optional.
      4. Enter the SQL statements, PL/SQL blocks and SQL*Plus commands you want to include in your script. Remember that SQL Command Line commands are ignored at run time.
      5. Click Save to save your script to the repository. The SQL Scripts page appears listing your newly saved script.

      Uploading a SQL Script

      To upload a script from your local file system:

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. Click the Upload button. The Upload Script dialog appears.
      3. To upload a script you can either:
        • Enter the name and path to the script you want to upload to the Script Repository.
        • Click Browse to locate the script you want to upload.
      4. Optionally rename the script by entering the new name in the Script Name field. This is the name given to the script in the Script Repository.
      5. Click Upload to add the script to the Script Repository. The SQL Scripts page appears listing your newly uploaded script. The script is parsed during upload. If it has a syntax error, an error icon appears in place of the run icon in the SQL Scripts page Details view. If a script of the same name exists in the Script Repository, you are prompted to rename it.

      Using the Script Editor

      You use the Script Editor to add content to a new script, to edit existing scripts, and to run and delete scripts in the script repository.

      Topics in this section include:

      • Editing an Existing Script
      • Searching and Replacing Text or Regular Expressions
      • Summary of Script Editor Controls

      Editing an Existing Script

      To edit a SQL script:

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. You can load a script into the editor as follows:
        • In Icons view, click the script icon.
        • In Details view, click the Edit icon.

      The Script Editor appears.

      • Search and Replace. Click Find to display the text and JavaScript regular expression find and replace options. Click Find again to hide the options. See «Searching and Replacing Text or Regular Expressions».
      • Line Selection. Click the line number on the left side of the Script Editor to select the associated line of your script for copying or deleting.
      • Cut, Copy, and Paste. Use standard edit controls to cut, copy and paste content in the Script Editor.
      • Auto indenting lines. New lines automatically indent to the previous line start column.

      You can test your script during editing by running the script to reveal errors. The Run Script dialog and the Script Results pages enable you to resume editing the script. See «Executing a SQL Script», and «Viewing SQL Script Results».

      Searching and Replacing Text or Regular Expressions

      Clicking the Find button in the Script Editor displays the Find and Replace with fields at the top of the page. Use these fields to search for and replace text strings and JavaScript regular expressions within a script. To exit Find mode, click Find again.

      To access Find mode in the Script Editor:

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. Select a script. The Script Editor appears.
      3. Click the Find button. The Find and Replace fields appear.
      4. In the Find field, enter the string you want to find. In Replace with, enter the new string to be added and then click the appropriate button (Replace, Find Next, or Replace All.) To further refine your search, select the appropriate check box:
        • Match Case
        • Match Whole Words
        • Match Regular Expression
      5. To exit Find mode, click Find .

      Summary of Script Editor Controls

      Table 2-1describes the buttons and controls available within the Script Editor

      Table 2-1 Buttons and Controls within the Script Editor

      Cancel the editing session and exit the Script Editor without saving changes made since the last save.

      Saves a copy of the current script to your local file system. Enter a name for the script on your local file system and a directory path.

      Removes the current script from the Script Repository.

      Save your changes to the current script to the Script Repository.

      Submits the script for execution.

      Removes, or undoes, the most recent line edit made in the Script Editor.

      Repeats the most recent line edit made in the Script Editor.

      Click Find to access search and replace mode. Click Find again to exit Find mode.

      Deleting a SQL Script

      You can delete scripts from the Script Repository by deleting selected scripts from the SQL Scripts page, or deleting the current script in the Script Editor.

      Topics in this section include:

      • Deleting Scripts from the SQL Scripts Page
      • Deleting a Script in the Script Editor

      Deleting Scripts from the SQL Scripts Page

      To delete scripts from the SQL Scripts page.

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. From the View list, select Details and click Go . Details view appears.
      3. Select the scripts to be deleted. To select individual scripts, click the check box to the left of the Edit icon. To select all scripts visible in the current page, click the check box in the column heading.
      4. Click Delete Checked to permanently remove the selected scripts from the Script Repository. You are prompted to confirm this action before the script is deleted. The message «Script(s) deleted» appears above the updated list of Scripts.

      Deleting a Script in the Script Editor

      To delete a script in the Script Editor:

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. Open the script you want to delete in the Script Editor.
      3. Click Delete to permanently remove the script from the Script Repository. You are prompted to confirm this action before the script is deleted. The SQL Scripts page appears. The message «Script(s) deleted» appears above the updated list of scripts.

      Copying a SQL Script

      You can copy a script in the Script Repository by saving it with a new name.

      To copy a script:

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. Load the script to copy into the editor.
      3. Enter a name for the copied script in the Script Name field.
      4. Click Save to save a copy of the script in the Script Repository. The SQL Scripts page appears listing the newly copied script.

      Executing a SQL Script

      You can execute scripts stored in the Script Repository. You can submit a script for execution either from the Script Editor, or from the SQL Scripts page.

      When you submit a script for execution, the Run Script page appears. It displays the script name, when it was created and by who, when it was last updated and by who, the number of statements it contains, and its size in bytes. It also lists unknown statements such as SQL*Plus commands that are ignored during execution.

      Finally, it lists statements with errors. If there are errors, the Run control does not appear.

      Topics in this section include:

      • Executing a SQL Script in the Script Editor
      • Executing a SQL Script from the SQL Scripts Page
      • About the Run Script Page

      Executing a SQL Script in the Script Editor

      To execute a script in the Script Editor:

      1. Open the script you want to execute in the Script Editor. See «Using the Script Editor».
      2. Click Run in the Script Editor.
      3. The Run Script page appears. The Run Script page displays information about the script and lists statements in error preventing execution, or statements such as SQL*Plus commands that are ignored when the script is executed. The Run Script page has three controls:
        • Cancel returns you to the SQL Scripts page without executing the script.
        • Edit Script loads the script into the Script Editor. Note that Edit Script appears instead of Run when a script has errors.
        • Run to submit the script for execution. Note that Run is not available if there are script errors.
      4. Click Run to submit the script for execution. The Manage Script Results page appears listing script results.
      5. To view script results, click the View icon under View Results.

      Executing a SQL Script from the SQL Scripts Page

      To execute a script from the SQL Scripts page:

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. From the View list, select Details and click Go . Details view appears.
      3. Click the Run icon for the script you want to execute. The Run icon is located on the far right side adjacent to the script name.
      4. The Run Script page appears. The Run Script page displays information about the script and lists statements in error preventing execution, or statements such as SQL*Plus commands that are ignored when the script is executed. The Run Script page has three controls: Cancel to return to the SQL Scripts page without executing the script. Edit Script to load the script into the Script Editor. Edit Script appears instead of Run when a script has errors. Run to submit the script for execution. Run is not available for scripts with errors.
      5. Click Run to submit the script for execution. The Manage Script Results page appears listing available results for the script.
      6. Click the View icon for the results you want to view. The View icon is at the right end of the scripts listed in the Manage Script Results page.

      About the Run Script Page

      On the Run Script page, you can:

      • Cancel the execution. Click Cancel to exit the Run Script page without executing the script. The SQL Scripts page appears.
      • Edit the script. Edit Script appears instead of Run when a script has errors. Click Edit Script to load the script into the Script Editor to remove the lines with errors.
      • Execute the script. Click Run to execute the script.

      Viewing SQL Script Results

      You use the Manage Script Results page to view and delete script results.

      You can also select script results to view from the Icons view of the SQL Scripts page, and from the Results column of the SQL Scripts page Details view.

      Topics in this section include:

      • Viewing Results from the SQL Scripts Page
      • About the Results Page

      Viewing Results from the SQL Scripts Page

      To view script results from the SQL Scripts page:

      1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
      2. You can access the Manage Script Results page in the following ways:
        • On the Tasks list, click Manage Results .
        • In Details view, click the Results number for the script you want to display.
        • In Icons view, click the Show Results check box and then the appropriate icon. Results icons only appear in the Icons view if you click the Show Results check box.

      The Manage Script Results page appears, listing available results for the script. See «About the Manage Script Results Page».

      About the Manage Script Results Page

      On the Manage Script Results page you can:

      • Search for a result. Enter a result name or partial name in the Script field and click Go . To view all results, leave the Script field blank and click Go . You control how many rows display by making a selection from the Display list.
      • Change the Page View. You can change the appearance of the page by making a selection from the View list. Available View options include:
        • Icons displays each result as an icon identified by the script name, and time and date stamp.
        • Details displays each result as a line in a report. Each line includes a check box to enable the selection of results for deletion, the associated script name which is a link enabling it to be loaded into the Script Editor, who ran the script, when the run started, how long it took to run, whether the run is complete or not, the number of statements executed, the size in bytes, and a View icon to view the results.

        About the Results Page

        The Results page displays the script name and status (Complete, Canceled, Executing or Submitted), and lists the statements executed.

        On the Results page you can:

        • Choose the view. Click the Detail or Summary option and click Go to specify whether to display complete or summarized information.
        • Choose the number of rows to display. In Summary view, make a selection from the Display list and click Go to specify the number of rows displayed.
        • Sort the statement report. In Summary view, select a column heading to sort the listed values by that column.
        • Edit the script. Click Edit Script to load the script into the Script Editor. See «Using the Script Editor».

        Exporting and Importing SQL Scripts

        You can transfer scripts from your current Script Repository to a Script Repository in a different workspace by using the Export and Import tasks. Exported scripts are encoded in a single file on your local file system. Once exported, you then log in to another workspace and import the file. During import, the file is run to re-create the scripts in the current Script Repository.

        By default, the Export SQL Scripts page lists all scripts in the Script Repository created by the current user. There are two panes on the Export SQL Scripts page, the Scripts pane and the Scripts to Export pane. You use the Scripts pane to select scripts to export. Then, you use the Scripts to Export pane to finalize the scripts to export, to choose a name for the export script, and to save the selected scripts in the export script on your local file system. You use the Import Scripts pane to select the export script containing the scripts to import.

        Topics in this section include:

        • Copying Scripts to an Export Script
        • Importing Scripts from an Export Script

        Copying Scripts to an Export Script

        To copy scripts to an export script:

        1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
        2. On the Tasks list, click Export . The Export SQL Scripts page appears.
        3. Click the check box for each of the scripts you want to export. The check boxes display on the left side adjacent to the script name. To select all displayed scripts for export, click the column head check box.
        4. Click Add to Export to create a list of scripts to be added to the export script. The selected scripts are added to the list of scripts in the Scripts to Export pane.
        5. Enter a name for the export script in the File Name field. The default script name is workspace_name _script.sql.
        6. Click Export All to export the scripts to the export script. You are prompted to enter the directory where you want to save the export script.
        About the Scripts Pane

        In the Scripts pane you can:

        • Search for a script. Enter a script name or partial name in the Find field and click Go . To view all scripts, leave the Find field blank, select — All Users — from the Owner list and click Go . You control how many rows display by making a selection from the Display list.
        • Cancel the export. Click Cancel to return to the SQL Scripts page without exporting any scripts, or to return to the SQL Scripts page after saving an export script.
        • Selecting scripts to export. Click Add to Export to add scripts to the export script. Scripts added to the export script are no longer listed in the Script pane, but appear in the Scripts to Export pane.
        • Sort scripts. Click a column heading to sort the listed scripts by that column.
        About the Scripts to Export Pane

        In the Scripts to Export pane you can:

        • Rename the export script. Enter a name for the export script in the File Name field or leave the default script name.
        • Remove scripts. Click the check box adjacent to the scripts you want to remove f and click Remove Checked . Scripts removed are no longer listed in the Scripts to Export pane, but appear in the Scripts pane.
        • Save the export script. Click Export All to save the export script to your local file system. You are prompted to enter the directory where you want to save the export script.

        Importing Scripts from an Export Script

        To import scripts from an export script:

        1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
        2. On the Tasks list, click Import . The Import Scripts pane appears. See «About the Import Scripts Pane».
        3. Enter the name and path to the export script you want to import to the Script Repository, or click Browse to locate the export script you want to import.
        4. Click Next to list the scripts in the export script. The Action column indicates whether the imported script is new, or whether it replaces an existing script of the same name.
        5. Click Import Script(s) to import the listed scripts into the current Script Repository. The SQL Scripts page appears listing the imported scripts.
        About the Import Scripts Pane

        In the Import Scripts pane you can:

        • Enter the export script. Enter the name and path of the script to import in the Import file field, or click Browse to locate the script.
        • Cancel the import. Click Cancel to return to the SQL Scripts page without importing scripts.
        • Proceed with the import. Click Next to import the scripts in the specified export script. You can review the listed scripts to import.
        • Choose another export file. Click Previous to return to the Import Scripts file selection page to choose a different export script.
        • Import the scripts. Click Import Script(s) to import the scripts contained in the export script.

        Viewing Script and Result Quotas

        You can view the script limits in the current workspace on the Script Quotas page.

        To view the Script Quotas page:

        1. On the Workspace home page, click SQL Workshop and then SQL Scripts . The SQL Scripts page appears.
        2. On the Tasks list, click Show Quotas . The Script Quotas page appears.
        3. Click OK to return to the SQL Scripts page.

        About the Script Quotas Page

        The Script Quotas page displays the following limits:

        • Result Quota in Bytes:
          • Maximum Script Result Size. The maximum size in bytes of a single script result.
          • Quota for All Script Results. The maximum size in bytes of all results in this workspace.
          • Used. The number of bytes currently used in this workspace.
          • Free. The number of bytes currently free in this workspace.
          • Quota. A usage bar illustrating the percentage of quota currently used.
          • Maximum Script Size. The maximum size in bytes of a single script. The size is set by the Oracle Application Express administrator and cannot be changed from within the Workspace.
          • Maximum Script Size. The maximum size in bytes of a single script.

          SQL сценарий

          Конфигурационный элемент типа SQL сценарий ( SQL script ) — это сущность, которая позволяет реализовать запрос к базе данных приложения с помощью языка SQL. Назначение SQL сценария — создание объектов (например, представлений, процедур, функций) базы данных или выполнение других запросов к базе данных приложения.

          Конфигурационный элемент типа SQL сценарий ( SQL script ), который позволяет добавить Creatio IDE, представлен значением выпадающего списка Добавить ( Add ) панели инструментов рабочей области раздела Конфигурация ( Configuration ).

          Подробнее о видах конфигурационных элементов читайте в статье Операции в Creatio IDE.

          Конфигурационный элемент типа SQL сценарий ( SQL script ) представлен значением SQL сценарий ( SQL script ) выпадающего списка Тип ( Type ) панели инструментов рабочей области раздела Конфигурация ( Configuration ).

          Тип SQL сценария представлен на рисунке ниже.

          Подробнее о типах конфигурационных элементов читайте в статье Операции в Creatio IDE.

          Реализовать SQL сценарий

          1. Перейдите в раздел Конфигурация ( Configuration ) и выберите пользовательский пакет, в который будет добавлен конфигурационный элемент.
          2. На панели инструментов реестра раздела нажмите Добавить —> SQL сценарий ( Add —> SQL script ).

            Код ( Code ) — название конфигурационного элемента (обязательное свойство). Шаблон, который необходимо использовать для названия SQL сценария, приведен ниже.
          [Префикс][Операция][Объект][СУБД]
          UsrUpdateActivityDateMSSQL
          • » BeforePackage » — SQL сценарий необходимо выполнить перед установкой пакета.
          • » AfterPackage » — SQL сценарий необходимо выполнить после установки пакета.
          • » AfterSchemaData » — SQL сценарий необходимо выполнить после установки данных (конфигурационные элементы типа Данные ( Data )) пакета.
          • » UninstallApp » — SQL сценарий, который выполняется при удалении из приложения пакета, которому принадлежит текущий SQL сценарий.

          Для применения изменений свойств нажмите Применить ( Apply ).

          Панель свойств дизайнера сценариев позволяет:

          • Изменить основные свойства конфигурационного элемента (кнопка ).
          • Задать дополнительные свойства конфигурационного элемента (кнопка ).

          Дополнительные свойства конфигурационного элемента:

          • Зависит от SQL сценариев ( Depends on SQL Scripts ) — позволяет выбрать SQL сценарии, которые необходимо выполнить до начала выполнения текущего сценария.
          • Зависимые SQL сценарии ( Dependent SQL Scripts ) — содержит SQL сценарии, выполнения которых необходимо начать после завершения выполнения текущего сценария. Заполняется автоматически и недоступно для редактирования.

          Чтобы выполнять SQL сценарии в установленном порядке:

          1. Выберите соответствующий тип установки (значение свойства Тип установки ( Installation type )).
          2. Установите необходимые зависимости между сценариями (свойства Зависит от SQL сценариев ( Depends on SQL Scripts ) и Зависимые SQL сценарии ( Dependent SQL Scripts )).

          Как SQL-скриптом сократить время ручного тестирования в 3 раза и облегчить жизнь коллегам

          Если ваша система использует БД и время от времени нужны тестовые записи, или если вы делаете insert-ы с несколькими наборами значений values, то изложенное ниже может пригодиться.

          Искать или создавать тестовые записи?

          Если у вас есть БД и вы разрабатываете алгоритмы, которые отбирают записи по определённым критериям из одной или нескольких таблиц, значит, на этапе разработки вам нужны тестовые данные, удовлетворяющие заданным условиям.

          Как же их получить? Первая мысль — найти среди уже имеющихся. Но, чем больше условий, тем больше проблем при поиске.

          Допустим, нашли. Разработчику и тестировщику нужно много вариантов набора данных. Можно взять несколько записей и их update-ить, но не помешает ли это кому-то ещё? Не грохнется ли часть данных по какой-нибудь причине? А что будет с этими записями через несколько месяцев, когда понадобится что-то перепроверить? На практике не раз сталкивался с худшими ответами на подобные вопросы. Как же этого избежать?

          Если мы знаем в какой таблице какие записи нужны, то самое логичное — делать insert-ы с нужными значениями, с оглядкой на все связи. Да, выглядит сложно и ресурсоёмко, но это только на первый взгляд.

          Раз уж мы начинаем разбираться в записях определённой таблицы, то всё равно придётся выяснить: какие в ней поля обязательные, какие связаны с другими таблицами, какие могут принимать значения и т.д.

          Всё это поможет написать скрипт, который вряд ли завалится из-за изменений в БД. К тому же, разбираться и писать скрипт будет один человек один раз, а использовать его можно будет многократно и кому угодно. Переменные, циклы, условные выражения и подзапросы позволят создать гибкий, легко читаемый и короткий скрипт, генерирующий готовый набор данных.

          Главная идея — запуском скрипта получать полный набор тестовых данных для одного или нескольких кейсов.

          Разберём на примере

          Покажу на Transact-SQL для MS SQL Server (на PostgreSQL будет аналогично). Допустим, есть таблица Trades. Нас интересуют данные за вчерашний день.

          Declare @i int, @n int = 5, -- сколько будет записей @TradeDate datetime = dateadd(day, -1, getdate()), @Market_id int = (select id from MarketDic where Code = 'Нужный'), @Currency_id int = (select top 1 id from CurrencyDic); set @i = 1; while (@i 
          1. Объявляем переменные:
            • i - для цикла
            • n - нужное количество записей
            • TradeDate - вчерашний день, получаемый вычитанием одного дня из текущей даты-времени
            • Market_id - поле, связанное с какой-то другой таблицей MarketDic. Берём значение id нужного нам Code
            • Currency_id - тоже связанное поле. Но, тут нас устроит любое значение, существующее в некой таблице CurrencyDic.
          2. Задаём значение i
          3. Пока выполняется условие, делаем insert-ы в нашу таблицу
            Поля:
            • id - вычисляем текущее максимальное значение id и увеличиваем его на 1
            • TradeDate - используем значение одноимённой переменной, т.е вчера
            • AccountName - объединяем в одну строку статичное "Имя_" со значением i. В результате, для соответствующих строк получим Имя_1, Имя_2, . Имя_5
            • DealType - для всех чётных строк (чей номер делится на 2 без остатка), значение будет "Buy", а для остальных - "Sell"
            • Market_id и Currency_id - значения одноимённых переменных, описанных выше.

          Итак, выполнив скрипт, мы за секунду получим готовый набор данных.

          Чем хорош скрипт:

          • Значение даты всегда нужное, не придётся update-ить
          • Всегда актуальные значения из связанных таблиц
          • Количество генерируемых записей легко меняется
          • Компактный вид
            Insert хотя бы 5 записей через набор значений values (. ), (. ), . (. ) получился бы гораздо длинней, большинство значений бы повторялось и читалось бы это всё тяжело.
          • Достаточно простая реализация
            Если уж Вы сюда добрались, скорее всего, про переменные и циклы представление у Вас имеется.
            Про getdate(), dateadd, concat, case. легко найти информацию в официальной документации и не только.

          Разумеется, на практике нужно несколько записей в нескольких таблицах, да и полей куда больше. Но, если разберётесь в моём примере, то ни количество таблиц, ни соотношение записей испугать Вас не должны.

          На что обратить внимание, при написании подобных скриптов

          Предварительное удаление

          Чтобы не засорять базу, хорошо бы каждым скриптом удалять записи, полученные от его предыдущего запуска.

          Для этого, между объявлением переменных и insert-ами, вставляем набор delete-ов.
          Соответственно, должна быть возможность отделять свои записи от любых других.
          Я применял 2 способа:

          • Текстовые метки
            В какой-нибудь из таблиц должно быть текстовое поле, куда можно прописать что-то говорящее, вроде "Test_for_Task-12345_1".
            Такие записи находятся через like 'Test_for_Task-12345_%' или просто равенством.
            Связанные с ней записи находятся вложенными select-ами и удаляются сначала они, а потом и главная.
            Может работать медленно, если данных много. Всё-таки like.
          • Заданный диапазон id-шников
            В качестве переменной задаём значение, далёкое от текущего, и от него отталкиваемся: в цикле к переменной прибавляем i.
            Зная сколько добавляем записей, потом ищем по id через between.

          Если тест кейсы автоматизируются, то удаление надо прописать так, чтобы оно выполнялось после завершения проверки (положительной или с падением).

          Вложенные циклы

          Почти наверняка нужно будет на одну запись в одной таблице сгенерить несколько в другой. Тут поможет вложенный цикл. Если используете свои id, то алгоритм вычисления id для него будет следующий:

          @id + @k + @n2 * (@i - 1)

          • id - вычисленное/желаемое изначальное значение
          • k - переменная внутри вложенного цикла
          • n2 - количество записей вложенного цикла (т.е, while вложенного цикла у нас с условием: k
          • i - переменная основного цикла
          Проверка наличия записи

          Может очень пригодиться конструкция: if not exists (select . )
          Т.е. если по какому-то запросу ничего не находится, то что-то выполняем.

          Типы переменных должны соответствовать типам полей

          При использовании переменных для заполнения полей, как в примере TradeDate, Market_id и Currency_id, их типы должны быть ровно те же, что у самих полей. Чтобы не получилось, что поле типа bigint, а переменная int.

          Вычисления внутри циклов

          Оставляйте минимум вычислений/подзапросов внутри циклов, чтобы они не создавали нагрузку при каждой итерации. В примере, id вычисляется каждый раз, т.к. иначе его не узнать, а Market_id и Currency_id - только при объявлении.

          Готовые select-ы

          В процессе написания скрипта, будете составлять select-ы, показывающие все сгенерированные записи. Сохраните их в конце, в закомментированном виде. Когда в следующий раз Вам, или кому-то из коллег, понадобится разобраться в скрипте, эти запросы сэкономят время.

          Результаты внедрения

          Что изменилось в работе нашей команды после того, как я опробовал на практике и рассказал коллегам об этом подходе к подготовке данных:

          • Время ручного тестирования одного из алгоритмов, на котором это обкатывалось, сократилось в 3-4 раза (до того мы находили несколько подходящих записей и update-или их).
          • Разработчикам и аналитикам стало легче.
            Разработчики использовали мои скрипты, чтобы было на чём отлаживаться.
            Аналитики - для подготовки к демо.
          • Ушла проблема разных справочников на разных стендах.
            Скрипт одинаково хорошо работал на всех, т.к. id-шники не зашиты хардкодом, а берутся запросами.
          • Автоматизировать тест кейсы с такими скриптами легко и быстро.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *