ANTON KADACH

All generations.

text to sql syntaxTue, 17 Jan 2023

Выгрузить все столбцы таблиц с описанием ВСЕХ типов полей по группам типов(например текст, JSONB, число, вещественное число) через case на русском языке. postgresql Выгрузить без пробелов и переносов. выгрузить одной строкой

SELECT string_agg(case data_type when 'character varying' then 'text' when 'integer' then 'integer' when 'double precision' then 'real' when 'jsonb' then 'jsonb' end,',') FROM information_schema.columns where table_schema='public' and table_name='customers';

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id) geo_object_attributes(geo_objects_id, name) запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку postgresql

WITH RECURSIVE geo_objects_tree (id, parent_id, name) AS ( SELECT id, parent_id, name FROM geo_objects UNION SELECT geo_objects.id, geo_objects.parent_id, geo_object_attributes.name FROM geo_objects_tree JOIN geo_objects ON geo_objects.id = geo_objects_tree.parent_id JOIN geo_object_attributes ON geo_object_attributes.geo_objects_id = geo_objects.id ) SELECT string_agg(name, ', ') FROM geo_objects_tree WHERE parent_id IS NULL;

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет дату и время актуальности у записи. нужную дату указывает пользователь. а у прошлой записи обновляется дата актуальности становится такая же , но на 1 секунду меньше. Входные параметры время, таблица в БД, массив идентификаторов. Plpgsql

CREATE OR REPLACE FUNCTION date_update(date_,table_,ids_) RETURNS void AS $BODY$ DECLARE i text; new_date timestamp; BEGIN new_date := date_; FOR i IN ARRAY ids_ LOOP EXECUTE 'UPDATE ' || quote_ident(table_) || ' SET date_actual = $1 where id = $2' USING new_date, i; new_date := new_date - interval '1 sec'; END LOOP; END; $BODY$ LANGUAGE plpgsql;

text to sql syntaxTue, 17 Jan 2023

Выгрузить все столбцы таблиц с описанием типов полей по группам типов(например текст, JSONB, число, вещественное число) через case на русском языке. postgresql пример CASE WHEN DATA_TYPE = 'character varying' THEN 'текст' WHEN DATA_TYPE = 'jsonb' THEN 'JSONB' WHEN DATA_TYPE = 'integer' THEN 'число' WHEN DATA_TYPE = 'numeric' THEN 'вещественное число' END AS DATA_TYPE

SELECT table_name, column_name, CASE WHEN DATA_TYPE = 'character varying' THEN 'text' WHEN DATA_TYPE = 'jsonb' THEN 'JSONB' WHEN DATA_TYPE = 'integer' THEN 'number' WHEN DATA_TYPE = 'numeric' THEN 'real number' END AS DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema='public'

text to sql syntaxTue, 17 Jan 2023

Geo_objects(id, level) geo_objects_attributes(id, name) geo_polygons(geo_id, simple_geometry) product_region(longitude, latitude, fias_id) запрос, который находит гео-объекты максимального level по координатам долготе и широте через функции ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)) в таблице geo_polygons и обновляет поле "fias_id" значением из поля external_id таблицы geo_objects_attributes в таблице product_region. Язык postgresql

WITH max_level AS ( SELECT MAX(level) AS level FROM geo_objects ), max_geo_id AS ( SELECT go.id AS geo_id FROM geo_objects go JOIN max_level ml ON ml.level = go.level ), max_geo_attr_id AS ( SELECT goa.id AS geo_attr_id FROM geo_objects_attributes goa JOIN max_geo_id mgi ON mgi.geo_id = goa.geo_id ), intersects_points AS ( SELECT DISTINCT p.fias_id AS fias_id, gpa.external_id AS external_id, p.id AS id FROM max_geo_id mgi JOIN geo_polygons gp ON gp.geo_id = mgi.geo_id JOIN product_region p ON ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point

text to sql syntaxTue, 17 Jan 2023

Функция plpgsql, которые находит все уникальные идентификаторы id из таблицы change_request_id, далее с циклом по таблице change_date ищет записи по change_request_id, копирует строки из change_data, создает их копию и связывает новые и старые строки между собой

CREATE OR REPLACE FUNCTION copy_change_data() RETURNS void LANGUAGE plpgsql AS $function$ DECLARE id_change_request_id integer; change_data_id_existing integer; change_data_id_new integer; BEGIN FOR id_change_request_id IN SELECT DISTINCT change_request_id FROM change_request_id LOOP FOR change_data_id_existing IN SELECT id FROM change_data WHERE change_request_id = id_change_request_id LOOP INSERT INTO change_data (name, change_request_id) VALUES ( (SELECT name FROM change_data WHERE id = change_data_id_existing), (SELECT change_request_id FROM change_data WHERE id = change_data_id_existing)); SELECT currval('change_data_id_seq'); change_data_id_new := currval('change_data_id_seq');

class from descriptionTue, 17 Jan 2023

создай класс "запрос на изменение" с полями номер запроса, имя запроса, дата создания и еще 10 полей

class ChangeRequest { public int Number {get;set;} public string Title {get;set;} public string CreatedDate {get;set;} public string ProjectName {get;set;} public string ProjectReleaseVersion {get;set;} public string ProjectReleaseDate {get;set;} public string CreatedByUser {get;set;} public string AssignedToUser {get;set;} public string Status {get;set;} public string Resolution {get;set;} public string RejectedReason {get;set;} }

text to sql syntaxWed, 18 Jan 2023

запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку

SELECT ( SELECT geoname FROM mfa_geo_object WHERE id = ( SELECT parent_id FROM mfa_geo_object WHERE id = ( SELECT parent_id FROM mfa_geo_object WHERE id = o.id ) ) ) as first, ( SELECT geoname FROM mfa_geo_object WHERE id = ( SELECT parent_id FROM mfa_geo_object WHERE id = o.id ) ) as second, ( SELECT geoname FROM mfa_geo_object WHERE id = o.id )

text to sql syntaxWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

sql syntax that: select all user from custoers with age 24 and name begin with letter a

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет version_actual_period_start с типом timestamp. Запись искать с условием version_actual_period_end > current_timestamp . нужную дату указывает пользователь, а у предыдущей, по времени актуальности записи, обновляется version_actual_period_end-становится такая же , но на 1 секунду меньше. Входные параметры время, наименование таблицы в БД, массив version_meta_id. Plpgsql

CREATE OR REPLACE FUNCTION public.upd_version_actual_period_start( p_date_start timestamp, p_table_name text, p_version_meta_ids integer[]) RETURNS void LANGUAGE 'plpgsql' VOLATILE COST 100 ROWS 1000 AS $BODY$ BEGIN FOR i IN 1..p_version_meta_ids[array_upper(p_version_meta_ids,1)] LOOP EXECUTE 'UPDATE ' || p_table_name || ' SET version_actual_period_start = ' || quote_literal(p_date_start) || ' WHERE version_actual_period_end > current_timestamp AND version_meta_id = ' || p_version_meta_ids[i] || ';'; EXECUTE 'UPDATE ' || p_table_name || ' SET version_actual_period_end = ' || quote_literal(p_date_start + interval '1' second) ||

text to sql syntaxTue, 17 Jan 2023

Функция plpgsql, которые находит все уникальные идентификаторы id из таблицы change_request_id, далее с циклом по таблице change_date ищет записи по change_request_id, копирует строки из change_data, создает их копию и связывает новые и старые строки между собой(link_change_data_id)

CREATE FUNCTION add_linked_change_data () RETURNS trigger AS $$ DECLARE change_data_id integer; change_request_id integer; old_change_data_id integer; old_change_request_id integer; field_name text; field_type integer; field_value text; link_change_data_id integer; link_change_request_id integer; BEGIN SELECT change_data_id, change_request_id, field_name, field_type, field_value INTO OLD; SELECT id INTO link_change_request_id FROM change_request WHERE id = OLD.change_request_id; SELECT id INTO link_change_data_id FROM change_data WHERE id = OLD.change_data_id; INSERT INTO change_data (field_name, field_type, field_value, link_change_data_id, link_change_request_id) VALUES (field_name, field_type, field_

text to sql syntaxTue, 17 Jan 2023

Функция plpgsql, которые находит все уникальные идентификаторы id из таблицы change_request_id, далее с циклом по таблице change_date ищет записи по change_request_id, копирует строки из change_data, создает их копию и связывает новые и старые строки между собой

create or replace function func_change_request() returns void as $$ DECLARE cr_id bigint; new_id bigint; old_id bigint; BEGIN for cr_id in (SELECT DISTINCT change_request_id from change_data) loop for old_id in (select id from change_data where change_request_id=cr_id) loop insert into change_data (change_request_id, change) select cr_id, change from change_data where id=old_id; select last_value into new_id from change_data_id_seq; insert into change_data_id (old_change_id, new_change_id) values (old_id, new_id); end loop; end loop;

testsTue, 17 Jan 2023

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) };

test('getParcelPickups', () => { const mockParcels = [ { merchantId: 1 }, { merchantId: 2 }, { merchantId: 3 }, ]; const mockWarehouses = [ { geoId: 1 }, { geoId: 2 }, { geoId: 3 }, ]; const mockPickupRegions = [ { geoId: 1 }, { geoId: 2 }, { geoId: 3 }, ]; cacheContainer.warehousesByMerchantId = new Map([ [1, [mockWarehouses[0]]], [2, [mockWarehouses[1]]], [3, [mockWarehouses[2]]], ]); cacheContainer.pickupRegionsByGeoId = new Map([ [1, mockPickupRegions[0]], [2, mockPickupRegions[1]], [3, mockPickupRegions[2]], ]); const

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

CREATE OR REPLACE FUNCTION version_replace_period_start(IN _version_meta_id bigint, OUT _time timestamp) RETURNS timestamp AS $BODY$ DECLARE _version_meta_id_current bigint; _version_meta_id_current_time_start timestamp; _version_meta_id_current_time_end timestamp; _time_end timestamp; BEGIN _version_meta_id_current= (select version_meta_id from version_actual_period where version_meta_id=_version_meta_id and version_actual_period_end>now()); _version_meta_id_current_time_start=( select version_actual_period_start from version_actual_period where version_meta_id=_version_meta_id_current); _version_meta_id_current_time_end=( select version_actual_period_end from version_actual_period

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет version_actual_period_start с типом timestamp. нужную дату указывает пользователь, а у предыдущей, по времени актуальности записи, обновляется version_actual_period_end-становится такая же , но на 1 секунду меньше. Входные параметры время, наименование таблицы в БД, массив version_meta_id. Plpgsql

UPDATE mytable SET version_actual_period_end=version_actual_period_start-1, version_actual_period_start=123 WHERE version_meta_id=1;

text to sql syntaxTue, 17 Jan 2023

Функция plpgsql, которые находит все уникальные идентификаторы id из таблицы change_request_id, далее с циклом по таблице change_date ищет записи по change_request_id, копирует строки из change_data, создает их копию и связывает новые и старые строки между собой(link_change_data_id)

CREATE OR REPLACE FUNCTION test_task_1() RETURNS void AS $$ DECLARE id integer; BEGIN FOR id IN (SELECT DISTINCT change_request_id FROM change_request_id) LOOP INSERT INTO change_request_id (change_request_id) SELECT nextval ('change_request_id_id_seq') AS id; INSERT INTO change_date (change_date, change_request_id) SELECT change_date, id FROM change_date WHERE change_request_id = id; INSERT INTO change_data (change_data_id, change_request_id, change_date_id, old_value, new_value) SELECT nextval ('change_data_id_seq'), id, link_change_data_id.id, old_value, new_value FROM change_data, change_date link_change_data_id WHERE change_request

text to sql syntaxTue, 17 Jan 2023

Функция plpgsql с курсором

CREATE OR REPLACE FUNCTION procedure_cursor() RETURNS VOID AS $$ DECLARE ref_cursor REFCURSOR; name TEXT; age INTEGER; BEGIN OPEN ref_cursor FOR SELECT * FROM customers; LOOP FETCH ref_cursor INTO name, age; EXIT WHEN NOT FOUND; RAISE NOTICE '%', name; RAISE NOTICE '%', age; END LOOP; CLOSE ref_cursor; END; $$ LANGUAGE plpgsql;

text to sql syntaxWed, 01 Feb 2023

напиши триггер на таблицу geo_polygons, который записывает удаление данных из таблицы. Записывая время изменения, пользователя кто вызвал операцию и идентификатор строки, которая удалилась. Plpgsql

CREATE OR REPLACE FUNCTION public.trg_geo_polygons_log_deletions() RETURNS trigger LANGUAGE plpgsql AS $function$ BEGIN INSERT INTO geo_table_log ( geo_table_id, geo_table, operation, username, operation_time, row_id) VALUES ( NEW.id, 'geo_polygons', 'delete', current_user, now(), OLD.id); RETURN NULL; END; $function$ ; CREATE TRIGGER trg_geo_polygons_log_deletions AFTER DELETE ON public.geo_polygons FOR EACH ROW EXECUTE PROCEDURE public.trg_geo_polygons_log_deletions();

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

CREATE OR REPLACE FUNCTION update_version_actual_period_start(time timestamp, table_name text, version_meta_id integer[]) RETURNS void AS$$ DECLARE a integer; BEGIN FOR a IN array_lower(version_meta_id, 1)..array_upper(version_meta_id, 1) LOOP update table_name set version_actual_period_end = time - interval '1 second' where version_meta_id = version_meta_id[a] and version_actual_period_end > current_timestamp; END LOOP; END; $$ LANGUAGE plpgsql;

code to explanationWed, 18 Jan 2023

with recursive r as ( select 1 as i,go2.parent_id , goa.id,goa."name",goa."type",goa.postal_code,goa.source_id,goa.external_id,goa.external_ids_history,goa.partition_code,goa.is_deleted,goa.timezone from geo_objects_attributes goa join geo_objects go2 on go2.id = goa.id where goa."type" ='Аобл' union select i+1 as i,go2.parent_id, goa.id,goa."name",goa."type",goa.postal_code,goa.source_id,goa.external_id,goa.external_ids_history,goa.partition_code,goa.is_deleted,goa.timezone from geo_objects_attributes goa join geo_objects go2 on go2.id = goa.id join r on r.id = go2.parent_id ) SELECT* from r JOIN geo_polygons gp ON gp.geo_id = r.id;

selecting geo_objects_attributes where geo_objects_attributes type is region. then selecting geo_objects_attributes where geo_objects_attributes type is city and parent_id is region_id. then repeating this until the last child is found(district)

text to sql syntaxWed, 01 Feb 2023

напиши функцию, которая проходит циклом по результату запроса SELECT id ,"name" FROM geo_objects_attributes goa и ищет результаты в таблице geo_objects go2, где go2.id = goa.id и показывает итог запроса . plpgsql

SELECT id ,"name" FROM geo_objects_attributes goa; SELECT go2.id, go2.name FROM geo_objects go2 INNER JOIN geo_objects_attributes goa ON go2.id = goa.id;

fix invalid codeTue, 17 Jan 2023

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) }; const getPickupFromParcel = async ({ warehouse, pickupRegion }) => { const isSelfDelivery = await selfDeliveryService.merchantHasSelfDelivery(warehouse.merchantId); const zeroMileTerminalGeoId = getZeroMileTerminalGeoId(pickupRegion); const zeroMile = zeroMileTerminalGeoId ? { terminalGeoId: zeroMileTerminalGeoId, carrierCode: getZeromileCarrierCode(pickupRegion, zeroMileTerminalGeoId) } : null; } const terminalGeoId = zeroMile ? zeroMile.terminalGeoId : warehouse.geoId; return { warehouse: warehouse.toTimeCalculatorFormat(), carrierCode: getCarrierCodeForPickup({ isSelfDelivery, zeroMile }), terminalGeo: terminalGeoId, withSortingCenter: Boolean(pickupRegion?.hasSortingCenter) }; const getCarrierCodeForPickup = ({ isSelfDelivery, zeroMile }) => { if (isSelfDelivery) { return config.selfDeliveryService.carrierCode; } if (zeroMile) { return zeroMile.carrierCode; } return null; }; const getZeromileCarrierCode = (pickupRegion, zeroMileTerminalGeoId) => { if (zeroMileTerminalGeoId) return pickupRegion.zeromileCarrierCode; return null; }; const getZeroMileTerminalGeoId = (pickupRegion) => { if (!pickupRegion) return null; if (isMoscow(pickupRegion)) return moscowId; if (isMoscowRegion(pickupRegion)) return moscowRegionId; return null; };

## License [MIT](https://github.com/shuvalov-anton/typescript-codestyle/blob/master/LICENSE)

translateTue, 17 Jan 2023

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) };

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) };

code to explanationWed, 01 Feb 2023

const { SessionFactory, Session, ConnectionFactory, Connection } = require("mp-database-pg"); const { geoServicePgConfig, geoServiceMappingChunckSize } = require("../config"); const GeoObject = require("../models/geoObject"); /** * @returns {Promise<Session>} created session */ const getSession = async () => await SessionFactory.createSession(geoServicePgConfig); /** * @returns {Promise<Connection>} created connection */ const getConnection = async () => await ConnectionFactory.createConnection(geoServicePgConfig); /** * * @param {*} dbObj * @returns {GeoObject} */ const toModel = dbObj => new GeoObject( Number(dbObj.id), dbObj.name, Number(dbObj.parent_id), Number(dbObj.level), dbObj.type, dbObj.postal_code, dbObj.has_childs ); const geoObjectLevels = { COUNTRY: 0, REGION: 1, AUTONOMOUS_REGION: 2, AREA: 3, SETTLEMENT: 35, CITY: 4, CITY_AREA: 5, LOCALITY: 6, PLANNING_STRUCTURE: 65, STREET: 7, ADDITIONAL_AREA: 90, ADDITIONAL_AREA_STREET: 91 }; /** * * @param {Session} session * @param {number[]} levels * @returns {Promise<GeoObject[]>} */ const getAll = async (session, levels) => ( await session.query( ` select obj.id, parent_id, level, name, type, postal_code from public.geo_objects obj, geo_objects_attributes attr where obj.is_deleted = false and obj.id = attr.id and level = any($levels) `, { levels } ) ).rows.map(toModel); /** * @param {Session} session * @param {Promise<Map<number, number>>} mappings */ const saveMappings = async (session, mappings) => { const columns = [ { name: "geo_id", prop: "geoId" }, { name: "osm_id", prop: "osmId" }, { name: "geometry", prop: "geometry", mod: ":raw" }, { name: "last_update", prop: "lastUpdate" } ]; await session.bulkUpsert(mappings, { columns, chunkSize: geoServiceMappingChunckSize, table: { schema: "public", table: "geo_polygons" }, onConflict: { columns: ["geo_id"] } }); }; /** * @param {Session} session * @returns {Promise} */ const clearOldMappings = async session => { await session.query("TRUNCATE TABLE public.geo_polygons"); }; const updatePoints = async session => { await session.query( `UPDATE public.geo_polygons SET centroid_point = ST_SetSRID(ST_Centroid(geometry), 3857) ` ); }; const updateSimplifiedPolygons = async (session, tolerance) => { await session.query( `UPDATE public.geo_polygons SET simple_geometry = ST_SetSRID(ST_SimplifyPreserveTopology(geometry, $tolerance), 3857) `, { tolerance } ); }; module.exports = { geoObjectLevels, getSession, getConnection, saveMappings, clearOldMappings, getAll, updatePoints, updateSimplifiedPolygons };

#### What type of requests are there? There are two types of requests: * A POST request to https://api.opencagedata.com/geocode/v1/json * A GET request to https://nominatim.openstreetmap.org/search #### What does the POST request to https://api.opencagedata.com/geocode/v1/json receive as input?

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

CREATE or REPLACE FUNCTION public.update_actual_period_start_by_time(time timestamp, version_meta_id int[], table_name text) RETURNS void LANGUAGE plpgsql AS $function$ declare sql_text text; begin sql_text := format('UPDATE %I SET version_actual_period_start = %L, version_actual_period_end = %L WHERE version_meta_id = ANY(%L);', table_name, time, time - interval '1 sec', version_meta_id); execute sql_text; end; $function$

class from descriptionTue, 17 Jan 2023

создай класс "запрос на изменение" с полями номер запроса, имя запроса, дата создания

public class ChangeRequest { private int _number; public int Number { get { return this._number; } set { this._number = value; } } private string _title; public string Title { get { return this._title; } set { this._title = value; } } private DateTime _creationDate; public DateTime CreationDate { get { return this._creationDate; } set { this._creationDate = value; } } public ChangeRequest(int number, string title, DateTime creationDate) { this.Number = number; this.Title = title; this.CreationDate = creationDate; } }

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет version_actual_period_start с типом timestamp. Запись искать с условием version_actual_period_end > current_timestamp . нужную дату указывает пользователь, а у предыдущей, по времени актуальности записи, обновляется version_actual_period_end-становится такая же , но на 1 секунду меньше. Входные параметры время, наименование таблицы в БД, массив version_meta_id. Plpgsql

text to sql syntaxWed, 01 Feb 2023

напиши функцию, которая проходит циклом по результату запроса SELECT id ,"name" FROM geo_objects_attributes goa и ищет результаты в таблице geo_objects go2, где go2.id = goa.id. По завершению функция выводит итог запроса . plpgsql

CREATE OR REPLACE FUNCTION get_geo_objects_attributes_by_id(id_var int) RETURNS TABLE (id int, name text) AS $$ BEGIN RETURN QUERY SELECT id, name FROM geo_objects_attributes goa WHERE goa.id = id_var; END; $$ LANGUAGE plpgsql; SELECT get_geo_objects_attributes_by_id(4);

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

CREATE OR REPLACE FUNCTION public.update_version_actual_period_start( IN p_time timestamp, IN p_table_name character varying, IN p_version_meta_id integer[]) RETURNS integer AS $BODY$ declare l_count integer; l_version_actual_period_start timestamp; l_version_actual_period_end timestamp; BEGIN l_count = 0; FOR i IN 1..array_length(p_version_meta_id, 1) LOOP SELECT version_actual_period_start, version_actual_period_end INTO l_version_actual_period_start, l_version_actual_period_end FROM $1 WHERE version_meta_id = p_version_meta_id[i]; IF (l_version_actual_period_end > current_timestamp) THEN l_count = l_count + 1; l_version_actual_period_start = p_time;

code to explanationWed, 18 Jan 2023

create or replace function add_in_group_versions( current_id_gp int8, link_code text)--current_id_gp int8, RETURNS void LANGUAGE plpgsql AS $function$ declare ver_id int8; begin select v.id from change_request."version" v join gp_project gp on gp.version_id= v.id where v.version_is_actual and gp.code in ($2) into ver_id; insert into change_request.group_versions (group_id, version_id) select distinct gv2.group_id , ver_id from change_request.group_versions gv join change_request.group_versions gv2 on gv2.group_id = gv.group_id join change_request."groups" g on g.id = gv2.group_id join gp_project gp on gp.version_id =g.version_id where gp.id = $1 on conflict do nothing; END; $function$ ;

## API: ![Alt text](images/api_diagram.png) ## How to make a request: * To get the list of groups:

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

CREATE OR REPLACE FUNCTION update_version_meta_table( in v_table_name character varying, in v_version_meta_id integer[], in v_current_timestamp timestamp) RETURNS void AS $BODY$ BEGIN UPDATE version_meta SET version_actual_period_end = v_current_timestamp- INTERVAL '1 second' WHERE version_actual_period_end > v_current_timestamp AND id = ANY (v_version_meta_id) AND version_table_name = v_table_name; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100;

text to sql syntaxWed, 18 Jan 2023

The recursive part of the query builds a table r that has all objects at all levels. This is done by iteratively joining the table itself with the geo_objects_attributes and geo_objects tables. The top level region is added in the first part of the union (select 1) and then the geo_objects_attributes and geo_objects tables are joined with the table r itself. This is done for all levels of the hierarchy. In the end, the result is simply joined with the geo_polygons table.

with recursive r as ( select root.id as id, root.name as name, root.level as level, root.parent_id as parent_id, root.id as parent_name, 1 as path_len from geo_objects root where root.parent_id is null union all select a.id as id, a.name as name, a.level as level, a.parent_id as parent_id, r.parent_name as parent_name, path_len + 1 as path_len from geo_objects a join r on a.parent_id = r.id ) select r.id, r.name, r.level, r.parent_id, r.parent_name, r.path_len, g.id as geo_polygon_id, ST_AsGeoJSON(geo_polygon) as geo_polygon from r left outer join geo_polygons g on r.id = g.object_id where r.level = 4 order by r.id;

code to explanationWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

### How to run 1. `npm i` 2. `npm run build` 3. `npm run start` 4. `npm run test` ### How to run with docker 1. `docker build -t js_to_md .` 2. `docker run -it js_to_md` ### How to run with docker (for lazy) `docker run -it mushinsky/js_to_md` ### Further work 1. Replace

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id) geo_object_attributes(id, name) запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку

SELECT group_concat(object_name) FROM geo_objects g JOIN geo_object_attributes o ON g.id=o.id WHERE g.parent_id=0 UNION ALL SELECT group_concat(object_name) FROM geo_objects g JOIN geo_object_attributes o ON g.id=o.id WHERE g.parent_id!=0;

time complexityWed, 15 Mar 2023

написать калькулятор

1. O(1) - нахождение элемента по индексу 2. O(n) - поиск минимального элемента в массиве 3. O(n^2) - сортировка вставками 4. O(n^3) - поиск максимальной суммы в массиве 5. O(log n) - бинарный поиск 6. O(n!) - перебор всех возможных вариантов

code to explanationWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

## <a name="how_to_run"></a>How to Run ### <a name="how_to_run_app"></a>How to run application 1. Install [Docker](https://docs.docker.com/install/) and [Docker Compose](https://docs.docker.com/compose/install/) 2. Clone project

code to explanationWed, 18 Jan 2023

create or replace function add_in_group_versions( current_id_gp int8, link_code text)--current_id_gp int8, RETURNS void LANGUAGE plpgsql AS $function$ declare ver_id int8; begin select v.id from change_request."version" v join gp_project gp on gp.version_id= v.id where v.version_is_actual and gp.code in ($2) into ver_id; insert into change_request.group_versions (group_id, version_id) select distinct gv2.group_id , ver_id from change_request.group_versions gv join change_request.group_versions gv2 on gv2.group_id = gv.group_id join change_request."groups" g on g.id = gv2.group_id join gp_project gp on gp.version_id =g.version_id where gp.id = $1 on conflict do nothing; END; $function$;

This function is intended to add a new group in the group_versions table. The function takes two arguments: the id of the group whose links are to be added and the code of the links to be added. The function returns nothing. The function select the id of the version in which the link is stored and stores it into the variable ver_id. If a link is in more than one version, the version with the highest id is selected. If the link is not loaded in the database, the function returns nothing. Then the function inserts the id of the group and the id of the version in which the link is stored (ver_id) into the group_versions table. The group_versions table stores the links (identified by their id in the table versions) of the groups (identified by their id in the table groups). If a group is in more than one version, the function stores the different versions.

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет version_actual_period_start с типом timestamp. Запись искать с условием version_actual_period_end > current_timestamp . нужную дату указывает пользователь, а у предыдущей, по времени актуальности записи, обновляется version_actual_period_end-становится такая же , но на 1 секунду меньше. Входные параметры время, наименование таблицы в БД, массив version_meta_id. Plpgsql

UPDATE :table SET version_actual_period_end=date_trunc('second',:date)-interval '1 second' WHERE version_actual_period_end > current_timestamp AND version_meta_id = ANY(:id);

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

CREATE OR REPLACE FUNCTION update_period_start( time_new timestamp, table_name text, -- table name version_meta_id int[] -- version_meta_id array ) RETURNS void AS $BODY$ DECLARE table_name_temp text; -- temporary table name version_meta_id_temp int[]; -- temporary version_meta_id array new_version_meta_id_temp int[]; -- new temporary version_meta_id array counter integer; -- counter time_current timestamp; -- current_timestamp time_old timestamp; -- previous timestamp BEGIN counter := 1; table_name_temp := 'temp_' || table_name; version_meta_id_temp := version_meta_id; time_current := current_timestamp; -- creating a temporary table EXECUTE 'CREATE TEMP TABLE ' || table_name_temp || ' (LIKE ' || table_name || ' INCLUDING ALL)'; --

generate functionTue, 17 Jan 2023

Напиши функцию, которая будет записывать историю действий мышкой в браузере и потом повторяла действия

using System; using System.Threading; using System.Reflection; using System.Reflection.Emit; using System.Windows.Forms; using System.Diagnostics; namespace MouseTracks { class MouseTracks { static void Main(string[] args) { Console.WriteLine("Mouse Track v0.1"); Console.WriteLine("----------------"); Console.WriteLine("1. Record"); Console.WriteLine("2. Playback"); Console.WriteLine("3. Exit"); Console.Write("Enter Choice: "); try { int i = int.Parse(Console.ReadLine()); switch (i) { case 1: Record(); break; case 2: PlayBack(); break; case 3: break; default: Console.WriteLine("Invalid Choice."); break; } } catch (FormatException) { Console.

code to explanationWed, 18 Jan 2023

update projectteam set version_actual_period_end = '2021-03-31 18:00:00' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675)-- вставляем сюда id без фигурных скобов and version_actual_period_end ='2021-04-01 09:47:03'; update projectteam --аналогично set version_actual_period_start = '2021-03-31 18:00:01', object_create_date = '2021-03-31 18:00:01' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end > current_timestamp ;

Вставляем сюда id без фигурных скобов и без запятых и в поле version_actual_period_end и в поле object_create_date указываем дату создания в будущем

code to explanationWed, 18 Jan 2023

const isSelfDelivery = await selfDeliveryService.merchantHasSelfDelivery(warehouse.merchantId); const zeroMileTerminalGeoId = getZeroMileTerminalGeoId(pickupRegion); const zeroMile = zeroMileTerminalGeoId ? { terminalGeoId: zeroMileTerminalGeoId, carrierCode: getZeromileCarrierCode(pickupRegion, zeroMileTerminalGeoId) } : null; } const terminalGeoId = zeroMile ? zeroMile.terminalGeoId : warehouse.geoId;

The above code checks whether the merchant has self delivery and if it does, it returns the first terminalGeoId (which is the geoId of the warehouse) else, it checks if there is a zero mile terminal and if it is, it returns the terminalGeoId of the zero mile terminal else it returns the geoId of the warehouse.

code to explanationWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

The function UPDATE_VERSION_ID (DP_ID INT) takes one argument DP_ID INT and returns the VOID.

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

CREATE OR REPLACE FUNCTION update_version_actual_period_start( time timestamp, table_name varchar(255), version_meta_id int ) RETURNS void AS $$ BEGIN EXECUTE format( ' UPDATE %I SET version_actual_period_end = time - interval ''1 seconds'' WHERE time > current_timestamp AND version_actual_period_end > current_timestamp AND version_meta_id = %L ', table_name, version_meta_id ); END; $$ LANGUAGE plpgsql;

text to sql syntaxWed, 18 Jan 2023

with cte as ( select cr.section_display, array_agg(cr.changed_entity_id)as ar from barsup_change_request.change_record cr join barsup_change_request.change_request_change_proposal_link plink on plink.change_proposal_id =cr.change_proposal_id join barsup_change_request.change_request creq on creq.id = plink.change_request_id where creq."number" = 'G1-4-2021/005' group by section_display) update reg_proj_fin_source rpfs -- меняем тут раздел 1 set version_actual_period_end = '2021-07-30 18:00:00' -- тут менять where version_meta_id in (select unnest(ar) from cte where section_display = 'Финансовое обеспечение') and version_actual_period_end ='2021-08-02 05:42:14'; -- тут поменять дату окончания with cte as ( select cr.section_display, array_agg(cr.changed_entity_id)as ar from barsup_change_request.change_record cr join barsup_change_request.change_request_change_proposal_link plink on plink.change_proposal_id =cr.change_proposal_id join barsup_change_request.change_request creq on creq.id = plink.change_request_id where creq."number" = 'G1-4-2021/005' group by section_display) update reg_proj_fin_source rpfs --аналогично set version_actual_period_start = '2021-07-30 18:00:01' where version_meta_id in (select unnest(ar) from cte where section_display = 'Финансовое обеспечение') and version_actual_period_end > current_timestamp and version_actual_period_start >'2021-08-02 05:42:14';

text to sql syntaxTue, 17 Jan 2023

Функция plpgsql с циклом по таблице change_request, которая принимает значение id, копирует строки из change_data, создает их копию и связывает новые и старые строки между собой

CREATE OR REPLACE FUNCTION public.copy_change_request_data(id int) RETURNS void AS $BODY$ DECLARE cr_rec record; cr_new_data_id integer; BEGIN FOR cr_rec IN SELECT * FROM change_request WHERE id = $1 LOOP INSERT INTO change_data(change_request_id,jsonb) VALUES(cr_rec.id,cr_rec.data) RETURNING id INTO cr_new_data_id; INSERT INTO change_data_history(change_data_id,change_request_id,jsonb) VALUES(cr_new_data_id,cr_rec.id,cr_rec.data); END LOOP; END; $BODY$ LANGUAGE plpgsql;

text to sql syntaxWed, 18 Jan 2023

The recursive part of the query builds a table r that has all objects at all levels. This is done by iteratively joining the table itself with the geo_objects_attributes and geo_objects tables. The top level region is added in the first part of the union (select 1) and then the geo_objects_attributes and geo_objects tables are joined with the table r itself. This is done for all levels of the hierarchy. In the end, the result is simply joined with the geo_polygons table.

WITH RECURSIVE r AS ( SELECT 1 AS level, id, name, parent_id FROM geo_objects_attributes WHERE parent_id IS NULL UNION ALL SELECT r.level + 1, geo_objects_attributes.id, geo_objects_attributes.name, geo_objects_attributes.parent_id FROM geo_objects_attributes, r WHERE geo_objects_attributes.parent_id = r.id ) SELECT r.id, r.name, geo_polygons.polygon FROM r LEFT JOIN geo_polygons ON r.id = geo_polygons.object_id;

text to sql syntaxWed, 01 Feb 2023

напиши функцию, которая проходит циклом по результату запроса SELECT id ,"name"FROM geo_objects_attributes goa в таблице geo_objects go2, где go2.id = goa.id и показывает итог запроса . plpgsql

CREATE OR REPLACE FUNCTION insert_sp (id, name) RETURNS void AS $$ BEGIN FOR i IN SELECT id, "name" FROM geo_objects_attributes goa WHERE goa.id = id LOOP RAISE NOTICE '%.%', i.id, i.name; END LOOP; END; $$ LANGUAGE plpgsql;

text to sql syntaxTue, 17 Jan 2023

Geo_objects(id, level) geo_objects_attributes(id, name) geo_polygons(geo_id, simple_geometry) product_region(longitude, latitude, fias_id) запрос, который находит гео-объекты максимального level по координатам долготе и широте через функции ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)) в таблице geo_polygons и обновляет поле "fias_id" значением из поля external_id таблицы geo_objects_attributes в таблице product_region. в одну строку Язык postgresql

UPDATE product_region AS p SET fias_id = g_a.external_id FROM geo_polygons AS gp INNER JOIN geo_objects AS g_o ON g_o.id = gp.geo_id INNER JOIN geo_objects_attributes AS g_a ON g_a.id = g_o.id WHERE ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)) AND g_o.level = (SELECT MAX(level) FROM geo_objects);

fix invalid codeWed, 18 Jan 2023

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) }; const getPickupFromParcel = async ({ warehouse, pickupRegion }) => { const isSelfDelivery = await selfDeliveryService.merchantHasSelfDelivery(warehouse.merchantId); const zeroMileTerminalGeoId = getZeroMileTerminalGeoId(pickupRegion); const zeroMile = zeroMileTerminalGeoId ? { terminalGeoId: zeroMileTerminalGeoId, carrierCode: getZeromileCarrierCode(pickupRegion, zeroMileTerminalGeoId) } : null; } const terminalGeoId = zeroMile ? zeroMile.terminalGeoId : warehouse.geoId; return { warehouse: warehouse.toTimeCalculatorFormat(), carrierCode: getCarrierCodeForPickup({ isSelfDelivery, zeroMile }), terminalGeo: terminalGeoId, withSortingCenter: Boolean(pickupRegion?.hasSortingCenter) }; const getCarrierCodeForPickup = ({ isSelfDelivery, zeroMile }) => { if (isSelfDelivery) { return config.selfDeliveryService.carrierCode; } if (zeroMile) { return zeroMile.carrierCode; } return null; }; const getZeromileCarrierCode = (pickupRegion, zeroMileTerminalGeoId) => { if (zeroMileTerminalGeoId) return pickupRegion.zeromileCarrierCode; return null; }; const getZeroMileTerminalGeoId = (pickupRegion) => { if (!pickupRegion) return null; if (isMoscow(pickupRegion)) return moscowId; if (isMoscowRegion(pickupRegion)) return moscowRegionId; return null; };

## Commands | Command | Effect | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ctrl+shift+p | Show command palette | | ctrl+o | Search for file | | ctrl+shift+o | Search for symbol | | ctrl+g | Navigate to line | | ctrl+shift+g | Navigate to last change | | c

text to sql syntaxTue, 17 Jan 2023

Выгрузить все столбцы таблиц с описанием типов полей по группам типов(например текст, JSONB, число, вещественное число) через case на русском языке. postgresql

SELECT TABLE_NAME, CASE WHEN DATA_TYPE = 'character varying' THEN 'текст' WHEN DATA_TYPE = 'jsonb' THEN 'JSONB' WHEN DATA_TYPE = 'integer' THEN 'число' WHEN DATA_TYPE = 'numeric' THEN 'вещественное число' END AS DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='public' AND TABLE_NAME='customers';

code to explanationWed, 18 Jan 2023

update projectteam set version_actual_period_end = '2021-03-31 18:00:00' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end ='2021-04-01 09:47:03'; update projectteam set version_actual_period_start = '2021-03-31 18:00:01', object_create_date = '2021-03-31 18:00:01' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end > current_timestamp ;

The function add takes two arguments a and b and returns the sum of a and b.

code to explanationWed, 18 Jan 2023

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) }; const getPickupFromParcel = async ({ warehouse, pickupRegion }) => { const isSelfDelivery = await selfDeliveryService.merchantHasSelfDelivery(warehouse.merchantId); const zeroMileTerminalGeoId = getZeroMileTerminalGeoId(pickupRegion); const zeroMile = zeroMileTerminalGeoId ? { terminalGeoId: zeroMileTerminalGeoId, carrierCode: getZeromileCarrierCode(pickupRegion, zeroMileTerminalGeoId) } : null; } const terminalGeoId = zeroMile ? zeroMile.terminalGeoId : warehouse.geoId; return { warehouse: warehouse.toTimeCalculatorFormat(), carrierCode: getCarrierCodeForPickup({ isSelfDelivery, zeroMile }), terminalGeo: terminalGeoId, withSortingCenter: Boolean(pickupRegion?.hasSortingCenter) }; const getCarrierCodeForPickup = ({ isSelfDelivery, zeroMile }) => { if (isSelfDelivery) { return config.selfDeliveryService.carrierCode; } if (zeroMile) { return zeroMile.carrierCode; } return null; }; const getZeromileCarrierCode = (pickupRegion, zeroMileTerminalGeoId) => { if (zeroMileTerminalGeoId) return pickupRegion.zeromileCarrierCode; return null; }; const getZeroMileTerminalGeoId = (pickupRegion) => { if (!pickupRegion) return null; if (isMoscow(pickupRegion)) return moscowId; if (isMoscowRegion(pickupRegion)) return moscowRegionId; return null; };

## Usage

code to explanationWed, 18 Jan 2023

create or replace function add_in_group_versions( current_id_gp int8, link_code text)--current_id_gp int8, RETURNS void LANGUAGE plpgsql AS $function$ declare ver_id int8; begin select v.id from change_request."version" v join gp_project gp on gp.version_id= v.id where v.version_is_actual and gp.code in ($2) into ver_id; insert into change_request.group_versions (group_id, version_id) select distinct gv2.group_id , ver_id from change_request.group_versions gv join change_request.group_versions gv2 on gv2.group_id = gv.group_id join change_request."groups" g on g.id = gv2.group_id join gp_project gp on gp.version_id =g.version_id where gp.id = $1 on conflict do nothing; END; $function$ ;

### Link to the project's wiki page: [Link to the wiki page](https://github.com/Git

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

CREATE OR REPLACE FUNCTION p_update_version_actual_period() RETURNS TRIGGER AS $$ declare version_meta_id integer; l_table_name text; l_version_actual_period_start timestamp; begin SELECT version_meta_id INTO version_meta_id FROM version_meta WHERE version_meta_id = NEW.version_meta_id; SELECT table_name INTO l_table_name FROM version_meta WHERE version_meta_id = NEW.version_meta_id; SELECT version_actual_period_start INTO l_version_actual_period_start FROM version_meta WHERE version_meta_id = NEW.version_meta_id; UPDATE version_meta SET version_actual_period_end = NEW.version_actual_period_start WHERE version_actual_period_end > current_timestamp; INSERT INTO version_meta(version_meta_id, version_actual_period_start, version_actual_period_end, table_name, version_status_id) VAL

text to sql syntaxWed, 18 Jan 2023

перепиши красиво with cte as ( select cr.section_display, array_agg(cr.changed_entity_id)as ar from barsup_change_request.change_record cr join barsup_change_request.change_request_change_proposal_link plink on plink.change_proposal_id =cr.change_proposal_id join barsup_change_request.change_request creq on creq.id = plink.change_request_id where creq."number" = 'G1-4-2021/005' group by section_display) update reg_proj_fin_source rpfs -- меняем тут раздел 1 set version_actual_period_end = '2021-07-30 18:00:00' -- тут менять where version_meta_id in (select unnest(ar) from cte where section_display = 'Финансовое обеспечение') and version_actual_period_end ='2021-08-02 05:42:14'; -- тут поменять дату окончания with cte as ( select cr.section_display, array_agg(cr.changed_entity_id)as ar from barsup_change_request.change_record cr join barsup_change_request.change_request_change_proposal_link plink on plink.change_proposal_id =cr.change_proposal_id join barsup_change_request.change_request creq on creq.id = plink.change_request_id where creq."number" = 'G1-4-2021/005' group by section_display) update reg_proj_fin_source rpfs --аналогично set version_actual_period_start = '2021-07-30 18:00:01' where version_meta_id in (select unnest(ar) from cte where section_display = 'Финансовое обеспечение') and version_actual_period_end > current_timestamp and version_actual_period_start >'2021-08-02 05:42:14';

# Памятка по терминам ## СУБД Система управления базой данных (СУБД) — программная система, которая обеспечивает хранение и управление базой данных, состоящей из набора автономных объектов, предназначенных для хранения и

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id) geo_object_attributes(geo_objects_id, name) geo_objects связана с таблицей geo_object_attributes geo_objects_id= id запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку postgresql

WITH RECURSIVE recursive_query AS ( SELECT id, name, parent_id FROM geo_objects WHERE parent_id IS NULL UNION ALL SELECT g.id, g.name, g.parent_id FROM geo_objects g INNER JOIN recursive_query r ON r.id = g.parent_id ) SELECT (SELECT string_agg(name, ', ') FROM recursive_query) as name_all FROM geo_objects

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет version_actual_period_start с типом timestamp. нужную дату указывает пользователь, а у предыдущей, по времени актуальности записи, обновляется version_actual_period_end-становится такая же , но на 1 секунду меньше. Входные параметры время, наименование таблицы в БД, массив version_meta_id. Plpgsql

CREATE OR REPLACE FUNCTION update_version_actual_period(IN date date, IN table_name text, IN version_meta_id integer[]) RETURNS void AS $$ DECLARE _id integer; _period_start timestamp; BEGIN FOR _id IN SELECT UNNEST(version_meta_id) LOOP SELECT version_actual_period_start INTO _period_start FROM table_name WHERE version_meta_id=_id; UPDATE table_name SET version_actual_period_start=date, version_actual_period_end=_period_start + interval '1 second' WHERE version_meta_id=_id; END LOOP; END; $$ LANGUAGE plpgsql;

text to sql syntaxTue, 17 Jan 2023

Geo_objects(id, level) geo_objects_attributes(id, name) geo_polygons(geo_id, simple_geometry) product_region(longitude, latitude, fias_id) запрос, который находит по координатам долготе и широте через функции ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)) в таблице geo_polygons и выбирает из результата строку с максимальным level из таблицы geo_objects и обновляет поле "fias_id" значением из поля external_id таблицы geo_objects_attributes в таблице product_region

UPDATE product_region p SET fias_id = (SELECT ga.external_id FROM geo_objects go INNER JOIN geo_polygons gp ON go.id = gp.geo_id INNER JOIN geo_objects_attributes ga ON ga.id=go.id WHERE ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)) order by go.level desc limit 1) WHERE fias_id IS NULL;

code to explanationWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

## if-elif-else:

code to explanationWed, 18 Jan 2023

update projectteam -- меняем тут раздел set version_actual_period_end = '2021-03-31 18:00:00' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675)-- вставляем сюда id без фигурных скобов and version_actual_period_end ='2021-04-01 09:47:03'; update projectteam --аналогично set version_actual_period_start = '2021-03-31 18:00:01', object_create_date = '2021-03-31 18:00:01' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675)--аналогично and version_actual_period_end > current_timestamp ;

text to sql syntaxTue, 17 Jan 2023

Geo_objects(id, level) geo_objects_attributes(id, name) geo_polygons(geo_id, simple_geometry) product_region(longitude, latitude, fias_id) запрос, который находит гео-объекты максимального level по координатам долготе и широте через функции ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)) в таблице geo_polygons и обновляет поле "fias_id" значением из поля external_id таблицы geo_objects_attributes в таблице product_region. Язык postgresql

UPDATE product_region p SET fias_id=goa.external_id FROM geo_polygons gp, geo_objects go, geo_objects_attributes goa WHERE gp.geo_id = go.id AND go.id = goa.id AND go.level = (select max(go.level) from geo_objects go where ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857))

fix invalid codeWed, 18 Jan 2023

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) }; const getPickupFromParcel = async ({ warehouse, pickupRegion }) => { const isSelfDelivery = await selfDeliveryService.merchantHasSelfDelivery(warehouse.merchantId); const zeroMileTerminalGeoId = getZeroMileTerminalGeoId(pickupRegion); const zeroMile = zeroMileTerminalGeoId ? { terminalGeoId: zeroMileTerminalGeoId, carrierCode: getZeromileCarrierCode(pickupRegion, zeroMileTerminalGeoId) } : null; } const terminalGeoId = zeroMile ? zeroMile.terminalGeoId : warehouse.geoId; return { warehouse: warehouse.toTimeCalculatorFormat(), carrierCode: getCarrierCodeForPickup({ isSelfDelivery, zeroMile }), terminalGeo: terminalGeoId, withSortingCenter: Boolean(pickupRegion?.hasSortingCenter) }; const getCarrierCodeForPickup = ({ isSelfDelivery, zeroMile }) => { if (isSelfDelivery) { return config.selfDeliveryService.carrierCode; } if (zeroMile) { return zeroMile.carrierCode; } return null; }; const getZeromileCarrierCode = (pickupRegion, zeroMileTerminalGeoId) => { if (zeroMileTerminalGeoId) return pickupRegion.zeromileCarrierCode; return null; }; const getZeroMileTerminalGeoId = (pickupRegion) => { if (!pickupRegion) return null; if (isMoscow(pickupRegion)) return moscowId; if (isMoscowRegion(pickupRegion)) return moscowRegionId; return null; };

js const getPickupFromParcel = async ({ warehouse, pickupRegion }) => { const isSelfDelivery = await selfDeliveryService.merchantHasSelfDelivery(warehouse.merchantId); const zeroMileTerminalGeoId = getZeroMileTerminalGeoId(pickupRegion); const zeroMile = zeroMileTerminalGeoId ? { terminalGeoId: zeroMileTerminalGeoId, carrierCode: getZeromileCarrierCode(pickupRegion, zeroMileTerminalGeoId) } : null; return { warehouse: warehouse.toTimeCalculatorFormat(), carrierCode: getCarrierCodeForPickup({ isSelfDelivery, zeroMile }), terminalGeo: getTerminalGeoId({ isSelfDelivery, zeroMile, warehouse }), withSortingCenter: Boolean(pickupRegion?.hasSortingCenter) }; }; const getCarrierCodeForPickup = ({ isSelfDelivery, zeroMile })

text to sql syntaxTue, 17 Jan 2023

Выгрузить все столбцы таблиц с описанием ВСЕХ типов полей по группам типов(например текст, JSONB, число, вещественное число) через case на русском языке. postgresql Выгрузить без пробелов и переносов. выгрузить одной строкой

SELECT string_agg(format( CASE WHEN data_type LIKE '%char%' THEN 'text' WHEN data_type LIKE '%int%' THEN 'number' WHEN data_type LIKE '%money%' THEN 'money' WHEN data_type LIKE '%bool%' THEN 'boolean' WHEN data_type LIKE '%time%' THEN 'date' WHEN data_type LIKE '%json%' THEN 'jsonb' WHEN data_type LIKE '%float%' THEN 'float' WHEN data_type LIKE '%double%' THEN 'double' ELSE 'none' END,'%s %s'), ', ') FROM information_schema.columns;

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id) geo_object_attributes(id, name) запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку

SELECT name FROM geo_object_attributes WHERE id IN (SELECT id FROM geo_object_attributes WHERE parent_id IN (SELECT parent_id FROM geo_objects WHERE id IN (SELECT id FROM geo_objects WHERE parent_id IN (SELECT parent_id FROM geo_objects WHERE id=1729) ) ) )

text to sql syntaxTue, 17 Jan 2023

Функция plpgsql с циклом по таблице change_date, которая принимает значение change_request_id, копирует строки из change_data, создает их копию и связывает новые и старые строки между собой

CREATE OR REPLACE FUNCTION copy_change_data(change_request_id int) RETURNS void AS $$ DECLARE data_row customers%ROWTYPE; BEGIN FOR data_row IN SELECT * FROM change_data LOOP INSERT INTO customers(name, age, sex) VALUES(data_row.name, data_row.age, data_row.sex) RETURNING id INTO data_row.id; INSERT INTO change_data(change_request_id, id, name, age, sex) VALUES(change_request_id, data_row.id, data_row.name, data_row.age, data_row.sex); END LOOP; END; $$ LANGUAGE 'plpgsql';

fix invalid codeWed, 18 Jan 2023

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) }; const getPickupFromParcel = async ({ warehouse, pickupRegion }) => { const isSelfDelivery = await selfDeliveryService.merchantHasSelfDelivery(warehouse.merchantId); const zeroMileTerminalGeoId = getZeroMileTerminalGeoId(pickupRegion); const zeroMile = zeroMileTerminalGeoId ? { terminalGeoId: zeroMileTerminalGeoId, carrierCode: getZeromileCarrierCode(pickupRegion, zeroMileTerminalGeoId) } : null; } const terminalGeoId = zeroMile ? zeroMile.terminalGeoId : warehouse.geoId; return { warehouse: warehouse.toTimeCalculatorFormat(), carrierCode: getCarrierCodeForPickup({ isSelfDelivery, zeroMile }), terminalGeo: terminalGeoId, withSortingCenter: Boolean(pickupRegion?.hasSortingCenter) }; const getCarrierCodeForPickup = ({ isSelfDelivery, zeroMile }) => { if (isSelfDelivery) { return config.selfDeliveryService.carrierCode; } if (zeroMile) { return zeroMile.carrierCode; } return null; }; const getZeromileCarrierCode = (pickupRegion, zeroMileTerminalGeoId) => { if (zeroMileTerminalGeoId) return pickupRegion.zeromileCarrierCode; return null; }; const getZeroMileTerminalGeoId = (pickupRegion) => { if (!pickupRegion) return null; if (isMoscow(pickupRegion)) return moscowId; if (isMoscowRegion(pickupRegion)) return moscowRegionId; return null; };

### Examples #### Prettier

text to sql syntaxTue, 17 Jan 2023

Выгрузить все столбцы таблиц с описанием типов полей по группам типов(например текст, JSONB, число, вещественное число) через case на русском языке. postgresql CASE WHEN DATA_TYPE = 'character varying' THEN 'текст' WHEN DATA_TYPE = 'jsonb' THEN 'JSONB' WHEN DATA_TYPE = 'integer' THEN 'число' WHEN DATA_TYPE = 'numeric' THEN 'вещественное число' END AS DATA_TYPE

SELECT schema_name, table_name, column_name, data_type, character_maximum_length, is_nullable, column_default FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema NOT IN ('pg_catalog', 'information_schema') ORDER BY schema_name, table_name;

code to explanationWed, 18 Jan 2023

CREATE TABLE logs( log_id SERIAL PRIMARY KEY, date_edit TIMESTAMP NOT NULL, sql_text TEXT NOT NULL, old_value JSONB NOT NULL, user_name TEXT NOT NULL );

The table logs has five columns. log_id is the primary key and it has a serial data type, date_edit is the date and time of when the data was changed, sql_text is a text that contains the sql query that was used to change the data, old_value is a JSONB that contains the old data, user_name is a text that contains the name of the user who changed the data.

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

UPDATE version_meta SET version_actual_period_start = '2018-02-10 10:00:00', version_actual_period_end = '2018-02-13 10:00:00' WHERE version_meta_id = '1000';

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет version_actual_period_start с типом timestamp. нужную дату указывает пользователь. а у предыдущей по времени актуальности записи обновляется дversion_actual_period_end становится такая же , но на 1 секунду меньше. Входные параметры время, наименование таблицы в БД, массив version_meta_id. Plpgsql

CREATE OR REPLACE FUNCTION update_actual_period(IN date_actual timestamp, IN table_name text, IN arr_version_meta_id text[]) RETURNS void AS $BODY$ DECLARE version_meta_id int; prev_date_actual timestamp; BEGIN FOR version_meta_id IN SELECT * FROM unnest(arr_version_meta_id) LOOP SELECT MAX(version_actual_period_start) INTO prev_date_actual FROM table_name WHERE version_meta_id = version_meta_id; UPDATE table_name SET version_actual_period_end = prev_date_actual + interval '1 second' WHERE version_actual_period_start = prev_date_actual AND version_meta_id = version_meta_id; INSERT INTO table_name (version_meta_id, version_actual_period_start, version_actual_period_end) VALUES (version_meta_id, date_actual, null); END LOOP; END; $BODY$ LANG

text to sql syntaxWed, 01 Feb 2023

напиши функцию, которая проходит циклом по результату запроса SELECT id ,"name" FROM geo_objects_attributes goa и ищет результаты в таблице geo_objects go2, где go2.id = goa.id и показывает итог запроса . plpgsql

CREATE OR REPLACE FUNCTION find_all_geo_objects_attributes_in_go2() RETURNS void AS $$ DECLARE goa_object_id int; goa_name text; go2_name text; BEGIN FOR goa_object_id, goa_name IN SELECT id, "name" FROM geo_objects_attributes LOOP SELECT go2.name INTO go2_name FROM geo_objects go2 WHERE go2.id=goa_object_id; IF go2_name IS NOT NULL THEN RAISE NOTICE '% %', goa_name, go2_name; END IF; END LOOP; END; $$ LANGUAGE plpgsql;

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id), geo_object_attributes(geo_objects_id, name) geo_objects связана с таблицей geo_object_attributes geo_objects_id= id запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку postgresql

WITH RECURSIVE t(id, name, path) AS ( SELECT geo_objects.id, geo_objects.name, ARRAY[geo_objects.id] FROM geo_objects WHERE geo_objects.id = 2 UNION ALL SELECT geo_objects.id, geo_objects.name, path || geo_objects.id FROM geo_objects, t WHERE geo_objects.parent_id = t.id ) SELECT * FROM t;

code to explanationWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

- In the end of the article write the final code (with all changes). ## Versioning - When you have finished the article, mark it with `status: to_review`. - The article is reviewed by a colleague, it makes changes if necessary. - If the article does not need to be changed, it is marked with the `status: ready`. - If the article needs to be changed, the article is marked with the `status: in_progress`. - If the article has been changed, it is marked with `status: to_review`. - When the article has the status `ready`, it is possible to mark it with the `status: published`. ### Example 1. Create article:

code to explanationWed, 18 Jan 2023

update projectteam -- меняем тут раздел set version_actual_period_end = '2021-03-31 18:00:00' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675)-- вставляем сюда id без фигурных скобов and version_actual_period_end ='2021-04-01 09:47:03'; update projectteam --аналогично set version_actual_period_start = '2021-03-31 18:00:01', object_create_date = '2021-03-31 18:00:01' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675)--аналогично and version_actual_period_end > current_timestamp ;

You can also specify a language in the code block:

code to explanationWed, 18 Jan 2023

update projectteam set version_actual_period_end = '2021-03-31 18:00:00' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end ='2021-04-01 09:47:03'; update projectteam set version_actual_period_start = '2021-03-31 18:00:01', object_create_date = '2021-03-31 18:00:01' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end > current_timestamp ;

The above query is setting the actual end period and actual start period.

text to sql syntaxWed, 01 Feb 2023

функция, которая циклом проходится по всем регионам и сохраняет каждый цикл результат в файл. plpgsql

CREATE OR REPLACE FUNCTION add_data() RETURNS TABLE(regname text, number INT, salary INT) AS $BODY$ DECLARE regname text; number INT; salary INT; BEGIN FOR regname IN select name from region LOOP select count(name), sum(salary) from employee where region=regname INTO number, salary; RETURN NEXT; END LOOP; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100 ROWS 1000;

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

REFRESH TEMPORARY TABLE tmp_table_name;

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет version_actual_period_start с типом timestamp. нужную дату указывает пользователь. а у предыдущей по времени актуальности записи обновляется дversion_actual_period_end становится такая же , но на 1 секунду меньше. Входные параметры время, наименование таблицы в БД, массив version_meta_id. Plpgsql

CREATE OR REPLACE FUNCTION update_version_actual_period( IN new_date timestamp, IN tablename text, IN version_meta_ids smallint[] ) RETURNS void LANGUAGE 'plpgsql' AS $BODY$ BEGIN UPDATE tablename SET version_actual_period_end = new_date - interval '1 second' WHERE version_meta_id = ANY(version_meta_ids); INSERT INTO tablename VALUES ( ANY(version_meta_ids), new_date, 'infinity' ); END; $BODY$;

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id) geo_object_attributes(id, name) запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку postgresql

WITH RECURSIVE t(id, name, parent_id) AS ( SELECT id, name, parent_id FROM geo_objects WHERE parent_id IS NULL UNION SELECT t1.id, t1.name, t1.parent_id FROM t JOIN geo_objects t1 ON t.id = t1.parent_id) SELECT DISTINCT name FROM t;

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id) geo_object_attributes(geo_objects_id, name) geo_objects связана с таблицей geo_object_attributes geo_objects_id= id запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку postgresql

WITH RECURSIVE cte AS ( WITH RECURSIVE tree AS ( SELECT *, ARRAY[]::INTEGER[] AS path FROM geo_objects WHERE id = 1 UNION ALL SELECT o.*, path || o.id FROM geo_objects o JOIN tree ON o.parent_id = tree.id ) SELECT id, path FROM tree WHERE path IS NOT NULL ) SELECT cte.id, geo_object_attributes.name FROM cte LEFT JOIN geo_object_attributes ON cte.id = geo_object_attributes.geo_object_id ORDER BY cte.path;

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id) и geo_object_attributes(geo_objects_id, name). geo_objects связана с таблицей geo_object_attributes geo_objects_id= id запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку postgresql

with recursive cte as ( select id, parent_id, array[id] as path from geo_objects where id = 11 union all select t.id, t.parent_id, c.path || t.id from geo_objects as t join cte as c on t.parent_id = c.id ) select array_agg(id) as path, array_agg(name) as name from cte join geo_object_attributes on geo_objects_id = id group by 1, 2;

code to explanationWed, 01 Feb 2023

const { SessionFactory, Session, ConnectionFactory, Connection } = require("mp-database-pg"); const { geoServicePgConfig, geoServiceMappingChunckSize } = require("../config"); const GeoObject = require("../models/geoObject"); /** * @returns {Promise<Session>} created session */ const getSession = async () => await SessionFactory.createSession(geoServicePgConfig); /** * @returns {Promise<Connection>} created connection */ const getConnection = async () => await ConnectionFactory.createConnection(geoServicePgConfig); /** * * @param {*} dbObj * @returns {GeoObject} */ const toModel = dbObj => new GeoObject( Number(dbObj.id), dbObj.name, Number(dbObj.parent_id), Number(dbObj.level), dbObj.type, dbObj.postal_code, dbObj.has_childs ); const geoObjectLevels = { COUNTRY: 0, REGION: 1, AUTONOMOUS_REGION: 2, AREA: 3, SETTLEMENT: 35, CITY: 4, CITY_AREA: 5, LOCALITY: 6, PLANNING_STRUCTURE: 65, STREET: 7, ADDITIONAL_AREA: 90, ADDITIONAL_AREA_STREET: 91 }; /** * * @param {Session} session * @param {number[]} levels * @returns {Promise<GeoObject[]>} */ const getAll = async (session, levels) => ( await session.query( ` select obj.id, parent_id, level, name, type, postal_code from public.geo_objects obj, geo_objects_attributes attr where obj.is_deleted = false and obj.id = attr.id and level = any($levels) `, { levels } ) ).rows.map(toModel); /** * @param {Session} session * @param {Promise<Map<number, number>>} mappings */ const saveMappings = async (session, mappings) => { const columns = [ { name: "geo_id", prop: "geoId" }, { name: "osm_id", prop: "osmId" }, { name: "geometry", prop: "geometry", mod: ":raw" }, { name: "last_update", prop: "lastUpdate" } ]; await session.bulkUpsert(mappings, { columns, chunkSize: geoServiceMappingChunckSize, table: { schema: "public", table: "geo_polygons" }, onConflict: { columns: ["geo_id"] } }); }; /** * @param {Session} session * @returns {Promise} */ const clearOldMappings = async session => { await session.query("TRUNCATE TABLE public.geo_polygons"); }; const updatePoints = async session => { await session.query( `UPDATE public.geo_polygons SET centroid_point = ST_SetSRID(ST_Centroid(geometry), 3857) ` ); }; const updateSimplifiedPolygons = async (session, tolerance) => { await session.query( `UPDATE public.geo_polygons SET simple_geometry = ST_SetSRID(ST_SimplifyPreserveTopology(geometry, $tolerance), 3857) `, { tolerance } ); }; module.exports = { geoObjectLevels, getSession, getConnection, saveMappings, clearOldMappings, getAll, updatePoints, updateSimplifiedPolygons };

⚠️ **Note:** **README.md** > const { SessionFactory, Session, ConnectionFactory, Connection } = require("mp-database-pg"); > const { geoServicePgConfig, geoServiceMappingChunckSize } = require("../config"); > const GeoObject = require("../models/geoObject"); **geoServicePgConfig** > const geoServicePgConfig = { > user: "postgres", > password: "postgres", > host: "192.168.99.100", > port: 5432, > database: "geo_service_db" > }; **geoServiceMappingChunckSize** > const geoServiceMappingChunckSize = 1000; **GeoObject** > class GeoObject { > constructor(id, name, parentId, level, type, postalCode, hasChilds) { > this.id = id; > this.

text to sql syntaxWed, 18 Jan 2023

Напиши функцию, которая обновляет version_actual_period_start с типом timestamp. нужную дату указывает пользователь. а у предыдущей по времени актуальности записи обновляется дversion_actual_period_end становится такая же , но на 1 секунду меньше. Входные параметры время, наименование таблицы в БД, массив version_meta_id. Plpgsql

CREATE OR REPLACE FUNCTION funtest(int, varchar, bigint[]) RETURNS void AS $$ DECLARE version_meta_id bigint; version_actual_period_start timestamp without time zone; version_actual_period_end timestamp without time zone; version_actual_period_start_old timestamp without time zone; version_actual_period_end_old timestamp without time zone; version_actual_period_end_new timestamp without time zone; table_name varchar; i int; BEGIN i=0; table_name:=$2; version_actual_period_start=$1; version_actual_period_end_new=version_actual_period_start-1; FOR version_meta_id IN array_iterate($3) LOOP SELECT version_actual_period_start, version_actual_period_end INTO version_actual_period_start_old, version_actual_period_

code to explanationWed, 18 Jan 2023

update projectteam set version_actual_period_end = '2021-03-31 18:00:00' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end ='2021-04-01 09:47:03'; update projectteam --аналогично set version_actual_period_start = '2021-03-31 18:00:01', object_create_date = '2021-03-31 18:00:01' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end > current_timestamp ;

The SQL statement updates the end date of the project team.

code to explanationWed, 18 Jan 2023

update projectteam set version_actual_period_end = '2021-03-31 18:00:00' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end ='2021-04-01 09:47:03'; update projectteam --аналогично set version_actual_period_start = '2021-03-31 18:00:01', object_create_date = '2021-03-31 18:00:01' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end > current_timestamp ;

text to sql syntaxWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

#### create table with column that has a specific data type

class from descriptionTue, 17 Jan 2023

создай класс "запрос на изменение" с полями номер запроса, имя запроса, дата создания и еще 15 полей

public class RequestForChange { public int Id { get; set; } public string Title { get; set; } public DateTime CreatedDate { get; set; } public string Owner { get; set; } public string Category { get; set; } public string Phase { get; set; } public string Status { get; set; } public string ChangeType { get; set; } public string Priority { get; set; } public string Severity { get; set; } public string Version { get; set; } public string IsClosed { get; set; } public string Description { get; set; } public string Activity { get; set; } public string Incident { get; set; } public string Requestor { get; set; } }

text to sql syntaxWed, 18 Jan 2023

Таблицы geo_objects(id, parent_id) и geo_object_attributes(geo_objects_id, name). geo_objects связана с таблицей geo_object_attributes geo_objects_id= id запрос, который рекурсивно находит все гео-объекты по дереву и выводит наименование всех гео-объектов дерева в одну строку postgresql

WITH RECURSIVE o AS( SELECT a.id, a.parent_id, a.name FROM geo_object_attributes as a INNER JOIN geo_objects as b ON a.geo_objects_id = b.id WHERE parent_id=1 UNION ALL SELECT a.id, a.parent_id, a.name FROM geo_object_attributes a INNER JOIN o ON o.parent_id=a.id ) SELECT id, parent_id, name FROM o

code to explanationWed, 18 Jan 2023

update projectteam set version_actual_period_end = '2021-03-31 18:00:00' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end ='2021-04-01 09:47:03'; update projectteam set version_actual_period_start = '2021-03-31 18:00:01', object_create_date = '2021-03-31 18:00:01' where version_meta_id in (8630871692,8615995858,8616230213,8314866364,8630873229,8631041012,8456151603,8615405675) and version_actual_period_end > current_timestamp ;

The function add takes two arguments a and b and returns the sum of a and b.

text to sql syntaxWed, 01 Feb 2023

напиши функцию, которая проходит циклом по результату запроса SELECT id ,"name" FROM geo_objects_attributes goa и ищет результаты в таблице geo_objects go2, где go2.id = goa.id и показывает итог запроса . plpgsql

DO $$ DECLARE i integer; BEGIN FOR i IN SELECT id ,"name" FROM geo_objects_attributes goa LOOP SELECT * FROM geo_objects go2 WHERE go2.id = goa.id; END LOOP; END; $$

text to sql syntaxTue, 17 Jan 2023

Выгрузить все столбцы таблиц с описанием ВСЕХ типов полей по группам типов(например текст, JSONB, число, вещественное число) через case на русском языке. postgresql пример CASE WHEN DATA_TYPE = 'character varying' THEN 'текст' WHEN DATA_TYPE = 'jsonb' THEN 'JSONB' WHEN DATA_TYPE = 'integer' THEN 'число' WHEN DATA_TYPE = 'numeric' THEN 'вещественное число' END AS DATA_TYPE

SELECT c.relname, a.attname, format_type(a.atttypid, a.atttypmod), pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod, CASE WHEN a.atttypid = 'character varying' THEN 'текст' WHEN a.atttypid = 'jsonb' THEN 'JSONB' WHEN a.atttypid = 'integer' THEN 'число' WHEN a.atttypid = 'numeric' THEN 'вещественное число' END AS DATA_TYPE FROM pg_attribute a JOIN pg_class c ON a.attrelid = c.oid JOIN pg_namespace n ON c.relnamespace = n.oid LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum =

code to explanationWed, 18 Jan 2023

with recursive r as ( select 1 as i,go2.parent_id , goa.id,goa."name",goa."type",goa.postal_code,goa.source_id,goa.external_id,goa.external_ids_history,goa.partition_code,goa.is_deleted,goa.timezone from geo_objects_attributes goa join geo_objects go2 on go2.id = goa.id where goa."type" ='Аобл' union select i+1 as i,go2.parent_id, goa.id,goa."name",goa."type",goa.postal_code,goa.source_id,goa.external_id,goa.external_ids_history,goa.partition_code,goa.is_deleted,goa.timezone from geo_objects_attributes goa join geo_objects go2 on go2.id = goa.id join r on r.id = go2.parent_id ) SELECT* from r JOIN geo_polygons gp ON gp.geo_id = r.id;

The recursive part of the query builds a table r that has all objects at all levels. This is done by iteratively joining the table itself with the geo_objects_attributes and geo_objects tables. The top level region is added in the first part of the union (select 1) and then the geo_objects_attributes and geo_objects tables are joined with the table r itself. This is done for all levels of the hierarchy. In the end, the result is simply joined with the geo_polygons table.

text to sql syntaxTue, 17 Jan 2023

Запрос, который проверяет содержится ли наименование города из поля city в поле address. Из поля city убираются все типы гео-объектов в сокращенном виде. postgresql

SELECT * FROM customers WHERE LOWER(ltrim(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(city, 'Спб.', ''), 'Санкт-Петербур

text to sql syntaxWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

sql syntax that: ALTER TABLE customers ALTER COLUMN age TYPE VARCHAR(255);

class from descriptionTue, 17 Jan 2023

создай класс "запрос на изменение" с полями номер запроса, имя запроса, дата создания и еще 30 полей

public class ChangeRequest { public int Id { get; set; } public string Name { get; set; } public DateTime CreatedAt { get; set; } public User CreatedBy { get; set; } public User ApprovedBy { get; set; } public string Description { get; set; } public DateTime DueDate { get; set; } public string AssignedTo { get; set; } public int Priority { get; set; } public int Status { get; set; } public int Category { get; set; } public int Type { get; set; } public Customer Customer { get; set; } }

text to sql syntaxWed, 18 Jan 2023

CREATE OR REPLACE FUNCTION UPDATE_VERSION_ID (DP_ID INT) RETURNS VOID LANGUAGE PLPGSQL AS $FUNCTION$ DECLARE vers_id int8; vers_actual_id int8; pt_id int8; ptr_id int8; dps_id int8; dpsa_id int8; fsa_id int8; begin select version_id from departmental_project where id = $1 into vers_id; create temp table temp_ver_id on commit drop as select v3.id from change_request.group_versions v join change_request.groups g on g.id = v.group_id join change_request.group_versions v2 on v2.group_id =g.id join change_request.version v3 on v3.id = v2.version_id and v3.version_is_actual where v.version_id =vers_id ; --Задача for pt_id in update project_tasks set version_id = vers_id where departmental_project_id = $1 and version_id in (select id from temp_ver_id) returning id loop for ptr_id in update project_task_results set version_id = vers_id where project_task_id = pt_id and version_id in (select id from temp_ver_id) returning id loop for dps_id in update departmental_project_sources set version_id = vers_id where result_id = ptr_id and version_id in (select id from temp_ver_id) returning id loop for dpsa_id in update departmental_project_source_attributes set version_id = vers_id where departmental_project_source_id = dps_id and version_id in (select id from temp_ver_id) returning financial_source_attribute_id loop update financial_source_attributes set version_id = vers_id where id = dpsa_id and version_id in (select id from temp_ver_id); end loop; end loop; end loop; end loop; --Результат end; $FUNCTION$ ;

sql syntax that: INSERT INTO users(name, age, gender, country) VALUES ('John', 21, 'male', 'USA'), ('Linda', 22, 'female', 'Canada');

text to sql syntaxTue, 17 Jan 2023

Geo_objects(id, level) geo_objects_attributes(id, name) geo_polygons(geo_id, simple_geometry) product_region(longitude, latitude, fias_id) запрос, который находит гео-объекты максимального level по координатам долготе и широте через функции ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)) в таблице geo_polygons и обновляет поле "fias_id" значением из поля external_id таблицы geo_objects_attributes в таблице product_region. в одну строку Язык postgresql

UPDATE product_region SET fias_id = (SELECT external_id FROM geo_objects_attributes WHERE id = (SELECT geo_id FROM geo_polygons WHERE simple_geometry && ST_Transform(ST_SetSRID(ST_Point(product_region.longitude::numeric, product_region.latitude::numeric), 4326), 3857) AND geo_objects.level = (SELECT MAX(level) FROM geo_objects))) WHERE fias_id IS NULL;

fix invalid codeTue, 17 Jan 2023

const getParcelPickups = (parcels) => { return Promise.all( parcels.map((parcel) => { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); return getPickupFromParcel({ warehouse, pickupRegion }); })) };

const getParcelPickups = (parcels) => { const pickups = []; for (const parcel of parcels) { const [warehouse] = cacheContainer.warehousesByMerchantId.get(Number(parcel.merchantId)) || []; const pickupRegion = cacheContainer.pickupRegionsByGeoId.get(warehouse.geoId); pickups.push(getPickupFromParcel({ warehouse, pickupRegion })); } return Promise.all(pickups); };

text to sql syntaxWed, 18 Jan 2023

Write a function that updates version_actual_period_start with type timestamp. Look for an entry with the condition version_actual_period_end > current_timestamp . the user specifies the desired date, and the previous one, according to the time of the relevance of the record, is updated version_actual_period_end-becomes the same, but 1 second less. Input parameters time, database table name, version_meta_id array. Plpgsql

DROP FUNCTION IF EXISTS update_period_start_timestamp(timestamp, text, integer[]); CREATE OR REPLACE FUNCTION update_period_start_timestamp(timestamp, text, integer[]) RETURNS void LANGUAGE plpgsql AS $$ BEGIN UPDATE $2 SET version_actual_period_start=$1,version_actual_period_end=version_actual_period_start WHERE version_actual_period_end>NOW() AND version_meta_id=ANY($3); END; $$;

text to sql syntaxTue, 17 Jan 2023

Geo_objects(id, level) geo_objects_attributes(id, name) geo_polygons(geo_id, simple_geometry) product_region(longitude, latitude, fias_id) запрос, который находит гео-объекты максимального level по координатам долготе и широте через функции ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)) в таблице geo_polygons и обновляет поле "fias_id" значением из поля external_id таблицы geo_objects_attributes в таблице product_region. в одну строку Язык postgresql

UPDATE product_region p SET fias_id = (SELECT goa.external_id FROM geo_objects go, geo_polygons gp, geo_objects_attributes goa WHERE go.id = gp.geo_id AND go.id = goa.id AND go.level IN (SELECT max(level) FROM geo_objects WHERE ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857))) AND ST_Intersects(gp.simple_geometry , ST_Transform(ST_SetSRID(ST_Point(p.longitude::numeric, p.latitude::numeric), 4326), 3857)));

text to sql syntaxWed, 01 Feb 2023

напиши функцию, которая проходит циклом по результату запроса SELECT id ,"name" FROM geo_objects_attributes goa и ищет результаты в таблице geo_objects go2, где go2.id = goa.id и показывает итог запроса . plpgsql

DO $$ DECLARE rec record; BEGIN FOR rec IN SELECT id ,"name" FROM geo_objects_attributes goa LOOP SELECT go2.* FROM geo_objects go2 WHERE go2.id = rec.id ; END LOOP; END; $$ LANGUAGE plpgsql;

text to sql syntaxTue, 17 Jan 2023

Выгрузить все столбцы таблиц с описанием типов полей по группам типов(например текст, JSONB, число, вещественное число) через case на русском языке. postgresql CASE WHEN DATA_TYPE = 'character varying' THEN 'текст' WHEN DATA_TYPE = 'jsonb' THEN 'JSONB' WHEN DATA_TYPE = 'integer' THEN 'число' WHEN DATA_TYPE = 'numeric' THEN 'вещественное число' END AS DATA_TYPE

**Получить список команд: \h** **Получить список схем: \dn** **Получить список таблиц: \dt** **Получить список представлений: \dv** **Получить список функций: \df** **Получить список индексов: \di** **Получить список триггеров: \dl** ###

Questions about programming?Chat with your personal AI assistant