Skip to content

Optimize http writer #10

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 11 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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@ 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.

- In the `format_template` field of the output parameters, the variable `ColumnNames` is now available.

### Breaking changes

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

- The `Rows` variable in the `format_template` filed of the output parameters is now a two-dimensional array,
not a map.

## [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
92 changes: 56 additions & 36 deletions doc/en/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,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 @@ -189,53 +192,66 @@ Structure `output.params` for format `http`:
- `batch_size`: Number of data records sent in one request. Default is `1000`.
- `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:
- `format_template`: Template-based format for sending data, configured using templates.
There are 3 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.

Example value for the `format_template` field:

```yaml
format_template: |
{
"table_name": "{{ .ModelName }}",
"meta": {
"rows_count": {{ len .Rows }}
},
"rows": [
{{- range $i, $row := .Rows }}
{{- if $i}},{{ end }}
{
"id": {{ index $row "id" }},
"username": "{{ index $row "name" }}"
}
{{- end }}
]
}
```
* `ColumnNames` - array of column names.
* `Rows` - a two-dimensional array, where each outer element represents a table row,
and the inner element contains values of this row in the same order as `ColumnNames`.

Default value for the `format_template` field:

```yaml
format_template: |
{
"table_name": {{ .ModelName }},
"rows": {{ json .Rows }}
"rows": {{ rowsJson .ColumnNames .Rows }}
}
```

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

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 }}`.

Function calls:

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

The following is a list of additional functions available in certain template fields:

In the `template` field of `string` data type:

- `upper`: converts the string to upper case.
- `lower`: converts the string to lower case.

In the `format_template` field of the output parameters:

- `len`: returns the length of the element.
- `json`: converts the element to a JSON string.
- `rowsJson`: converts an array of column names (`ColumnNames`) and a two-dimensional array of rows (`Rows`)
into a JSON array whose elements are objects of the form:
```
{
"columnName1": value1,
"columnName2": value2,
...
}
```
where each object corresponds to one row of the table.

#### Examples of data generation configuration

Example data model configuration:
Expand Down Expand Up @@ -301,9 +317,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 Expand Up @@ -382,7 +402,7 @@ output:
"meta": {
"rows_count": {{ len .Rows }}
},
"rows": {{ json .Rows }}
"rows": {{ rowsJson .ColumnNames .Rows }}
}

models:
Expand Down
94 changes: 57 additions & 37 deletions doc/ru/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,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 @@ -195,53 +198,66 @@ open_ai:
- `batch_size`: Размер отправляемого в одном запросе массива данных. По умолчанию `1000`.
- `workers_count`: Количество потоков для записи данных. По умолчанию `1`. *Является экспериментальным полем.*
- `headers`: Заголовки http запроса, указываются в формате словаря. По умолчанию отсутствуют.
- `format_template`: Формат отправляемых данных, конфигурируемый с помощью шаблонов Golang.
Для использования в поле `format_template` доступны:

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

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

```yaml
format_template: |
{
"table_name": "{{ .ModelName }}",
"meta": {
"rows_count": {{ len .Rows }}
},
"rows": [
{{- range $i, $row := .Rows }}
{{- if $i}},{{ end }}
{
"id": {{ index $row "id" }},
"username": "{{ index $row "name" }}"
}
{{- end }}
]
}
```
* `ColumnNames` - массив имён колонок.
* `Rows` - двумерный массив, где каждый внешний элемент представляет строку таблицы,
а внутренний содержит значения этой строки в том же порядке, что и `ColumnNames`.

Значение поля `format_template` по умолчанию:

```yaml
format_template: |
{
"table_name": {{ .ModelName }},
"rows": {{ json .Rows }}
"table_name": "{{ .ModelName }}",
"rows": {{ rowsJson .ColumnNames .Rows }}
}
```

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

Структура `output.params` для формата `tcs`:

Подобна структуре для формата `http`, за исключением того,
что поле `format_template` неизменяемое и всегда равняется значению по умолчанию.

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

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

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

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

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

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

Ниже приведён список дополнительных функций, доступных в определённых полях шаблонов:

В поле `template` типа данных `string`:

- `upper`: преобразует строку в верхний регистр.
- `lower`: преобразует строку в нижний регистр.

В поле `format_template` параметров вывода:

- `len`: возвращает длину элемента.
- `json`: преобразует элемент в JSON строку.
- `rowsJson`: преобразует массив имён колонок (`ColumnNames`) и двумерный массив строк (`Rows`)
в JSON-массив, элементами которого являются объекты вида:
```
{
"columnName1": value1,
"columnName2": value2,
...
}
```
где каждый объект соответствует одной строке таблицы.

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

Пример конфигурации модели данных:
Expand Down Expand Up @@ -307,9 +323,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 Expand Up @@ -388,7 +408,7 @@ output:
"meta": {
"rows_count": {{ len .Rows }}
},
"rows": {{ json .Rows }}
"rows": {{ rowsJson .ColumnNames .Rows }}
}

models:
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