Skip to content

Improve string template #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [latest](https://github.com/tarantool/sdvg/compare/0.0.1..master)

### Changed

- The `template` field in the `string` data type is now used to generate template strings
with the ability to use the values of any columns of the generated model.

### Breaking changes

- Using `template` field to specify a string pattern like `Aa0#` is no longer supported,
`pattern` should be used instead.

## [0.0.1](https://github.com/tarantool/sdvg/compare/36d0930..0.0.1) - 2025-07-21

### Added
Expand Down
6 changes: 5 additions & 1 deletion config/models.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,13 @@ models:
- name: passport
type: string
type_params:
template: AA 00 000 000
pattern: AA 00 000 000
distinct_percentage: 1
ordered: true
- name: email
type: string
type_params:
template: "{{ .first_name_en | lower }}.{{ .id }}@email.com"
- name: created
type: datetime
type_params:
Expand Down
61 changes: 52 additions & 9 deletions doc/en/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,11 @@ Structure `models[*].columns[*].type_params` for data type `string`:
- `min_length`: Minimum string length. Default is `1`.
- `max_length`: Maximum string length. Default is `32`.
- `logical_type`: Logical type of string. Supported values: `first_name`, `last_name`, `phone`, `text`.
- `template`: Template for string generation. Symbol `A` - any uppercase letter, symbol `a` - any lowercase letter,
symbol `0` - any digit, symbol `#` - any character. Other characters remain as-is.
- `template`: Template for string generation. Allows you to use the values of any columns of the generated model.
Information about the functions available in template strings is described at the end of this section.
Cannot coexist with `ordered`, `distinct_percentage` and `distinct_count`.
- `pattern`: Pattern for string generation. The `A` symbol is any capital letter, the `a` symbol is any small letter,
symbol `0` is any digit, the `#` symbol is any character, and the other characters remain as they are.
- `locale`: Locale for generated strings. Supported values: `ru`, `en`. Default is `en`.
- `without_large_letters`: Flag indicating if uppercase letters should be excluded from the string.
- `without_small_letters`: Flag indicating if lowercase letters should be excluded from the string.
Expand Down Expand Up @@ -194,15 +197,12 @@ Structure `output.params` for format `http`:
- `workers_count`: Number of threads for writing data. Default is `1`. *Experimental field.*
- `headers`: HTTP request headers specified as a dictionary. Default is none.
- `format_template`: Template-based format for sending data, configured using Golang templates.
Available for use in `format_template`:

- fields:
There are 2 fields available for use in `format_template`:
* `ModelName` - name of the model.
* `Rows` - array of records, where each element is a dictionary representing a data row.
Dictionary keys correspond to column names, and values correspond to data in those columns.
- functions:
* `len` - returns the length of the given element.
* `json` - converts the given element to a JSON string.

You can read about the available functions and the use of template strings at the end of this section.

Example value for the `format_template` field:

Expand Down Expand Up @@ -240,6 +240,45 @@ Structure of `output.params` for `tcs` format:
Similar to the structure for the `http` format,
except that the `format_template` field is immutable and always set to its default value.

Using Template Strings:

Template strings are implemented using the standard golang library, you can read about
all its features and available functions in this [documentation](https://pkg.go.dev/text/template).

Accessing Data:

In a template, data is accessed using `.` (the object or value passed to the template)
and the field name, for example: `{{ .var }}`.

> **Important**: only the following characters are allowed in variable names:
>
> - letters from any alphabet (Unicode category L*).
> - numbers (Unicode category Nd), but not as the first character.
> - the underscore character `_`.
>
> Any other characters — spaces, periods, hyphens, quotation marks, punctuation marks,
etc. — cannot be used in the name itself.
>
> If you need to access a variable whose name is considered invalid,
refer to it using the `index` function, specifying the variable name in quotation marks, for example, `{{ index . "field-with-dash" }}`.

Function calls:

- direct call: `{{ upper .name }}`.
- using pipe: `{{ .name | upper }}`.

In addition to standard functions, the project provides `4` custom functions:

- `upper`: converts the string to upper case.
- `lower`: converts the string to lower case.
- `len`: returns the length of the element.
- `json`: converts the element to a JSON string.

Usage restrictions:

The `lower`, and `upper` functions are available only in the `template` field of the `string` data type.
The `len` and `json` functions are available only in the `format_template` field of the output parameters.

#### Examples of data generation configuration

Example data model configuration:
Expand Down Expand Up @@ -305,9 +344,13 @@ models:
- name: passport
type: string
type_params:
template: AA 00 000 000
pattern: AA 00 000 000
distinct_percentage: 1
ordered: true
- name: email
type: string
type_params:
template: "{{ .first_name_en | lower }}.{{ .id }}@example.com"
- name: rating
type: float
type_params:
Expand Down
61 changes: 52 additions & 9 deletions doc/ru/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,11 @@ open_ai:
- `min_length`: Минимальная длина строки. По умолчанию `1`.
- `max_length`: Максимальная длина строки. По умолчанию `32`.
- `logical_type`: Логический тип строки. Поддерживаемые значения: `first_name`, `last_name`, `phone`, `text`.
- `template`: Шаблон для генерации строки. Символ `A` - любая большая буква, символ `a` - любая маленькая буква,
символ `0` - любая цифра, символ `#` - любой символ. Остальные символы остаются как есть.
- `template`: Шаблон для генерации строки. Позволяет использовать значения любых столбов генерируемой модели.
Информация о том, как использовать шаблонные строки, описана в конце данного раздела.
Не работает совместно с `ordered`, `distinct_percentage` и `distinct_count`.
- `pattern`: Паттерн для генерации строки. Символ `A` - любая большая буква, символ `a` - любая маленькая буква,
символ `0` - любая цифра, символ `#` - любой символ, а остальные символы остаются как есть.
- `locale`: Локаль для генерации строк. Поддерживаемые значения: `ru`, `en`. По умолчанию `en`.
- `without_large_letters`: Флаг, указывающий, исключать ли большие буквы из строки.
- `without_small_letters`: Флаг, указывающий, исключать ли маленькие буквы из строки.
Expand Down Expand Up @@ -200,15 +203,12 @@ open_ai:
- `workers_count`: Количество потоков для записи данных. По умолчанию `1`. *Является экспериментальным полем.*
- `headers`: Заголовки http запроса, указываются в формате словаря. По умолчанию отсутствуют.
- `format_template`: Формат отправляемых данных, конфигурируемый с помощью шаблонов Golang.
Для использования в поле `format_template` доступны:

- поля:
Для использования в `format_template` доступно 2 поля:
* `ModelName` - имя модели.
* `Rows` - массив записей, где каждый элемент является словарем, который представляет собой строку данных.
Ключи словаря соответствуют названиям столбцов, а значения — данным в этих столбцах.
- функции:
* `len` - возвращает длину переданного элемента.
* `json` - преобразует переданный элемент в JSON строку.

О доступных функциях и использовании шаблонных строк можно прочитать в конце данного раздела.

Пример значения поля `format_template`:

Expand Down Expand Up @@ -246,6 +246,45 @@ open_ai:
Подобна структуре для формата `http`, за исключением того,
что поле `format_template` неизменяемое и всегда равняется значению по умолчанию.

Использование шаблонных строк:

Шаблонные строки реализованы с использованием стандартной библиотеки golang, ознакомиться
со всеми ее возможностями и доступными функциями можно данной [документации](https://pkg.go.dev/text/template).

Доступ к данным:

Обращение к данным в шаблоне выполняется с помощью `.` (объект или значение, переданное шаблону)
и имени переменной, например, `{{ .var }}`.

> **Важно**: в именах переменных допустимы только следующие символы:
>
> - буквы любого алфавита (Unicode-категории L*).
> - цифры (Unicode-категории Nd), но не первым символом.
> - знак подчёркивания `_`.
>
> Любые другие символы — пробелы, точки, дефисы, кавычки, символы пунктуации
и т.д. — в самом имени использовать нельзя.
>
> Если вам необходимо получить доступ к переменной, имя которой считается недопустимым,
обращайтесь к ней через функцию `index`, указав имя переменной в кавычках, например `{{ index . "field-with-dash" }}`.

Вызовы функций:

- прямой вызов: `{{ upper .name }}`.
- с помощью pipe: `{{ .name | upper }}`.

В проекте помимо стандартных функций доступны `4` пользовательских:

- `upper`: преобразует строку в верхний регистр.
- `lower`: преобразует строку в нижний регистр.
- `len`: возвращает длину элемента.
- `json`: преобразует элемент в JSON строку.

Ограничения по использованию:

Функции `lower`, и `upper` доступны только в поле `template` типа данных `string`.
Функции `len` и `json` доступны только в поле `format_template` параметров вывода.

#### Примеры конфигурации генерации данных

Пример конфигурации модели данных:
Expand Down Expand Up @@ -311,9 +350,13 @@ models:
- name: passport
type: string
type_params:
template: AA 00 000 000
pattern: AA 00 000 000
distinct_percentage: 1
ordered: true
- name: email
type: string
type_params:
template: "{{ .first_name_en | lower }}.{{ .id }}@example.com"
- name: rating
type: float
type_params:
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/labstack/echo/v4 v4.13.3
github.com/manifoldco/promptui v0.9.0
github.com/moby/term v0.5.2
github.com/otaviokr/topological-sort v1.1.0
github.com/pkg/errors v0.9.1
github.com/sashabaranov/go-openai v1.36.1
github.com/spf13/afero v1.12.0
Expand Down
Loading