Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
-- @desc: KOROK-224 (05/11/2026). Na R-4020 (efentradas × effornece × efimpent,
-- com codi_emp nas três e IN de duas empresas), a efimpent entrava num NestLoop
-- parametrizado só por codi_emp = effornece.codi_emp, e o codi_ent ficava como
-- Join Filter: cada entrada trazia do Sybase todos os impostos da empresa
-- (148 mil linhas descartadas em produção). Sem estatísticas, todo ppi_rows
-- vale 1 e as parametrizações empatavam; agora a que empurra mais cláusulas
-- custa menos.
-- @expect: ok

BEGIN;
SET LOCAL statement_timeout = '120s';

CREATE FUNCTION pg_temp.confere(ok boolean, msg text) RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
IF ok IS NOT TRUE THEN RAISE EXCEPTION 'falhou: %', msg; END IF;
END $$;

CREATE FUNCTION pg_temp.plano(sql text) RETURNS text
LANGUAGE plpgsql AS $$
DECLARE l text; r text := '';
BEGIN
FOR l IN EXECUTE 'EXPLAIN (VERBOSE, COSTS OFF) ' || sql LOOP
r := r || l || E'\n';
END LOOP;
RETURN r;
END $$;

CREATE TEMP TABLE consulta AS SELECT $q$
SELECT e.codi_emp, e.codi_ent, sum(i.vlor_ien) AS total
FROM dominio.ppi_ent e
JOIN dominio.ppi_for f ON f.codi_emp = e.codi_emp AND f.codi_for = e.codi_for
AND f.codi_emp IN (1, 2) AND f.tins_for IN (1, 4)
JOIN dominio.ppi_imp i ON i.codi_emp = e.codi_emp AND i.codi_ent = e.codi_ent
AND i.codi_emp IN (1, 2) AND i.codi_imp IN (16, 22, 23, 24, 25)
WHERE e.codi_emp IN (1, 2) AND e.dent_ent BETWEEN '2026-09-01' AND '2026-09-30'
GROUP BY 1, 2
$q$::text AS sql;

SELECT pg_temp.plano(sql) AS p FROM consulta \gset
SELECT pg_temp.confere(
:'p' NOT LIKE '%Join Filter: (i.codi_ent = e.codi_ent)%'
AND :'p' LIKE '%Foreign Scan on dominio.ppi_imp i%(i.codi_ent = e.codi_ent)%',
'efimpent sem o codi_ent no parâmetro: ' || :'p');

-- Mesmo resultado que o Hash Join, que lê cada tabela uma vez.
DO $$ BEGIN EXECUTE 'CREATE TEMP TABLE r1 AS ' || (SELECT sql FROM consulta); END $$;
SET LOCAL enable_nestloop = off;
DO $$ BEGIN EXECUTE 'CREATE TEMP TABLE r2 AS ' || (SELECT sql FROM consulta); END $$;
SELECT pg_temp.confere((SELECT count(*) FROM r1) = 60, 'esperava 60 entradas com imposto');
SELECT pg_temp.confere(NOT EXISTS (SELECT * FROM r1 EXCEPT SELECT * FROM r2)
AND NOT EXISTS (SELECT * FROM r2 EXCEPT SELECT * FROM r1), 'NestLoop e Hash Join divergem');

ROLLBACK;
15 changes: 15 additions & 0 deletions .ci/sybase-test-env/scripts/setup-pg.sql
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,21 @@ CREATE FOREIGN TABLE dominio.grande (
) SERVER sybase_test_server
OPTIONS (table 'bethadba.grande');

-- KOROK-224: forma da R-4020. `rows` com a ordem de grandeza de produção, para
-- o planner montar o mesmo plano (fixture 156).
DROP FOREIGN TABLE IF EXISTS dominio.ppi_ent, dominio.ppi_for, dominio.ppi_imp CASCADE;
CREATE FOREIGN TABLE dominio.ppi_ent (
codi_emp integer NOT NULL, codi_ent integer NOT NULL,
codi_for integer NOT NULL, dent_ent date NOT NULL
) SERVER sybase_test_server OPTIONS (table 'bethadba.ppi_ent', rows '937000');
CREATE FOREIGN TABLE dominio.ppi_for (
codi_emp integer NOT NULL, codi_for integer NOT NULL, tins_for integer
) SERVER sybase_test_server OPTIONS (table 'bethadba.ppi_for', rows '290000');
CREATE FOREIGN TABLE dominio.ppi_imp (
codi_emp integer NOT NULL, codi_ent integer NOT NULL,
codi_imp integer NOT NULL, vlor_ien numeric(15,2)
) SERVER sybase_test_server OPTIONS (table 'bethadba.ppi_imp', rows '1310000');

-- ============================================================================
-- Módulo de Folha (Payroll). Espelha a topologia em que os ex-pg_tests
-- consumiam tabelas Sybase reais — agora sustentado pelo schema em
Expand Down
28 changes: 28 additions & 0 deletions .ci/sybase-test-env/sql/03_prod_query_tables.sql
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,31 @@ CREATE TABLE bethadba.grande (
id INTEGER NOT NULL PRIMARY KEY,
texto VARCHAR(200)
);

-- ============================================================================
-- KOROK-224: forma da R-4020 (efentradas × effornece × efimpent, codi_emp nas
-- três). Ver fixture 156.
-- ============================================================================
DROP TABLE IF EXISTS bethadba.ppi_ent;
CREATE TABLE bethadba.ppi_ent (
codi_emp INTEGER NOT NULL,
codi_ent INTEGER NOT NULL,
codi_for INTEGER NOT NULL,
dent_ent DATE NOT NULL,
PRIMARY KEY (codi_emp, codi_ent)
);
DROP TABLE IF EXISTS bethadba.ppi_for;
CREATE TABLE bethadba.ppi_for (
codi_emp INTEGER NOT NULL,
codi_for INTEGER NOT NULL,
tins_for INTEGER,
PRIMARY KEY (codi_emp, codi_for)
);
DROP TABLE IF EXISTS bethadba.ppi_imp;
CREATE TABLE bethadba.ppi_imp (
codi_emp INTEGER NOT NULL,
codi_ent INTEGER NOT NULL,
codi_imp INTEGER NOT NULL,
vlor_ien NUMERIC(15,2),
PRIMARY KEY (codi_emp, codi_ent, codi_imp)
);
5 changes: 5 additions & 0 deletions .ci/sybase-test-env/sql/04_prod_query_data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,9 @@ COMMIT;
-- grande — 1 milhão de linhas de ~150 bytes.
INSERT INTO bethadba.grande SELECT row_num, repeat('x', 150) FROM sa_rowgenerator(1, 1000000);

-- ppi_* (KOROK-224) — 2 empresas: 1000 fornecedores, 3000 entradas, impostos em 300.
INSERT INTO bethadba.ppi_for SELECT e.v, r.row_num, 1 FROM sa_rowgenerator(1, 1000) r, (SELECT 1 v UNION ALL SELECT 2) e;
INSERT INTO bethadba.ppi_ent SELECT e.v, r.row_num, mod(r.row_num, 1000) + 1, DATEADD(day, mod(r.row_num, 300), '2026-01-01') FROM sa_rowgenerator(1, 3000) r, (SELECT 1 v UNION ALL SELECT 2) e;
INSERT INTO bethadba.ppi_imp SELECT e.v, r.row_num * 10, i.v, 1 FROM sa_rowgenerator(1, 300) r, (SELECT 1 v UNION ALL SELECT 2) e, (SELECT 16 v UNION ALL SELECT 25) i;

COMMIT;
13 changes: 12 additions & 1 deletion supabase-wrappers/src/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1168,7 +1168,18 @@
for ppi in seen_ppis {
let param_rows = (*ppi).ppi_rows;
let param_startup = startup_cost + fdw_startup_cost;
let param_total = param_startup + param_rows;
// KOROK-224: with no stats every ppi_rows clamps to 1 and the
// parameterizations tie; the planner kept the first one, e.g.
// efimpent by codi_emp only, bringing every tax of the company per
// outer row. Make the one that pushes more join clauses cheaper.
// shortcut: counts ppi clauses even if the deparse cannot push them;
// check pushability here if such a ppi ever wins a tie it shouldn't.
let clauses = if (*ppi).ppi_clauses.is_null() {
0
} else {
(*(*ppi).ppi_clauses).length
};
let param_total = param_startup + param_rows + 0.5_f64.powi(clauses);

let param_path = pg_sys::create_foreignscan_path(
root,
Expand Down Expand Up @@ -1252,7 +1263,7 @@
if !pg_sys::bms_is_subset(clause_relids, (*baserel).relids) {
// Join condition: add to fdw_exprs for replace_nestloop_params
let opexpr = expr as *mut pg_sys::OpExpr;
if let Some(args) =

Check failure on line 1266 in supabase-wrappers/src/scan.rs

View workflow job for this annotation

GitHub Actions / Run supabase_wrappers tests

this `if` statement can be collapsed

Check failure on line 1266 in supabase-wrappers/src/scan.rs

View workflow job for this annotation

GitHub Actions / Run supabase_wrappers tests

this `if` statement can be collapsed
pgrx::list::List::<*mut std::ffi::c_void>::downcast_ptr_in_memcx(
(*opexpr).args,
mcx,
Expand Down
Loading