@ancha-labs/cli 0.4.11 → 0.4.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,13 @@ var SIGNS = {
29
29
  ItemRcpt: [null, 1, 1],
30
30
  Journal: [null, 1, 1]
31
31
  };
32
+ var KEPT_DDL = `
33
+ CREATE TABLE ns_records (type TEXT NOT NULL, id INTEGER NOT NULL, externalid TEXT, fields TEXT NOT NULL DEFAULT '{}', PRIMARY KEY(type, id));
34
+ CREATE INDEX ns_records_externalid ON ns_records (type, externalid COLLATE NOCASE);
35
+ CREATE TABLE ns_record_types (type TEXT PRIMARY KEY);
36
+ CREATE TABLE ns_extra (owner TEXT NOT NULL, id INTEGER NOT NULL, fields TEXT NOT NULL DEFAULT '{}', PRIMARY KEY(owner, id));
37
+ CREATE TABLE ns_fields (recordtype TEXT NOT NULL, sublist TEXT NOT NULL DEFAULT '', field TEXT NOT NULL, owner TEXT NOT NULL, kind TEXT NOT NULL, target TEXT,
38
+ PRIMARY KEY(recordtype, sublist, field));`;
32
39
  var signed = (column, which) => `CASE t.type ${Object.entries(SIGNS).filter(([, s]) => s[which] !== null).map(([type, s]) => `WHEN '${type}' THEN ${s[which]} * ${column}`).join(" ")} ELSE NULL END`;
33
40
  var bool = (column) => `CASE ${column} WHEN 1 THEN 'T' ELSE 'F' END`;
34
41
  var NS_DDL = `
@@ -65,6 +72,7 @@ CREATE TABLE ns_applications (payment INTEGER NOT NULL, source INTEGER NOT NULL,
65
72
  doc INTEGER NOT NULL, docline INTEGER NOT NULL DEFAULT 0, amount REAL NOT NULL CHECK(amount > 0), PRIMARY KEY(payment, source, sourceline, doc, docline));
66
73
  CREATE INDEX ns_applications_source ON ns_applications (source, sourceline);
67
74
  CREATE INDEX ns_applications_target ON ns_applications (doc, docline);
75
+ CREATE INDEX ns_lines_item ON ns_lines (item);
68
76
  -- General ledger impact, rewritten whenever its transaction is saved: one row per account a line debits or credits.
69
77
  CREATE TABLE ns_gl (id INTEGER PRIMARY KEY AUTOINCREMENT, "transaction" INTEGER NOT NULL, line INTEGER NOT NULL, account INTEGER NOT NULL, debit REAL, credit REAL,
70
78
  entity INTEGER, department INTEGER, location INTEGER, class INTEGER, memo TEXT);
@@ -92,13 +100,14 @@ CREATE TABLE ns_oauth (token TEXT PRIMARY KEY, kind TEXT NOT NULL, client TEXT N
92
100
  CREATE INDEX ns_oauth_chain ON ns_oauth (chain);
93
101
  CREATE TABLE ns_sequences (recordtype TEXT PRIMARY KEY, next INTEGER NOT NULL);
94
102
  CREATE TABLE ns_history (ordinal INTEGER PRIMARY KEY AUTOINCREMENT, recordtype TEXT NOT NULL, id INTEGER NOT NULL, operation TEXT NOT NULL, at TEXT NOT NULL);
103
+ ${KEPT_DDL}
95
104
 
96
- -- What an invoice or bill still owes: its total less what payments, credits and deposit applications applied to it.
97
- CREATE VIEW ns_open AS SELECT t.id, t.total - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.doc = t.id), 0) AS unpaid FROM ns_transactions t;
98
- -- What a payment, credit or deposit has left: its total less what it applied, what refunds paid out of it and, for a deposit, what was applied from it.
99
- CREATE VIEW ns_unapplied AS SELECT t.id, t.total - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.source = t.id), 0)
105
+ -- What an invoice or bill still owes, in cents: its total less what payments, credits and deposit applications applied to it.
106
+ CREATE VIEW ns_open AS SELECT t.id, ROUND(t.total - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.doc = t.id), 0), 2) AS unpaid FROM ns_transactions t;
107
+ -- What a payment, credit or deposit has left, in cents: its total less what it applied, what refunds paid out of it and, for a deposit, what was applied from it.
108
+ CREATE VIEW ns_unapplied AS SELECT t.id, ROUND(t.total - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.source = t.id), 0)
100
109
  - COALESCE((SELECT SUM(a.amount) FROM ns_applications a WHERE a.doc = t.id), 0)
101
- - COALESCE((SELECT SUM(d.total) FROM ns_transactions d WHERE d.type = 'DepAppl' AND d.createdfrom = t.id), 0) AS unapplied FROM ns_transactions t;
110
+ - COALESCE((SELECT SUM(d.total) FROM ns_transactions d WHERE d.type = 'DepAppl' AND d.createdfrom = t.id), 0), 2) AS unapplied FROM ns_transactions t;
102
111
  -- Original open items, with opposite journal lines netted in original line order within each party/account.
103
112
  CREATE VIEW ns_item_original AS WITH raw AS (
104
113
  SELECT t.id AS doc, l.line, CASE a.accttype WHEN 'AcctRec' THEN 'receivable' ELSE 'payable' END AS side,
@@ -133,18 +142,18 @@ CREATE VIEW ns_stock AS
133
142
  CREATE VIEW ns_q_customer AS SELECT e.id, e.entityid, e.companyname, e.firstname, e.lastname, ${bool("e.isperson")} AS isperson,
134
143
  e.email, e.phone, e.fax, e.url, ${bool("e.isinactive")} AS isinactive, e.creditlimit, e.credithold, e.credithold AS creditholdoverride, e.terms, e.subsidiary, e.currency, e.comments,
135
144
  e.salesrep, e.externalid, e.datecreated, e.lastmodifieddate, e.extra,
136
- COALESCE((SELECT SUM(CASE i.role WHEN 'debt' THEN i.original ELSE -i.original END) FROM ns_item_original i WHERE i.side='receivable' AND i.entity=e.id AND i.currency=e.currency),0)
145
+ ROUND(COALESCE((SELECT SUM(CASE i.role WHEN 'debt' THEN i.original ELSE -i.original END) FROM ns_item_original i WHERE i.side='receivable' AND i.entity=e.id AND i.currency=e.currency),0)
137
146
  - COALESCE((SELECT SUM(t.total) FROM ns_transactions t WHERE t.type='DepAppl' AND t.entity=e.id AND t.currency=e.currency),0)
138
- + COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions p ON p.id=a.payment JOIN ns_transactions d ON d.id=a.doc WHERE p.type='CustRfnd' AND p.entity=e.id AND p.currency=e.currency AND d.type<>'CustDep'),0) AS balance,
139
- COALESCE((SELECT SUM(o.unpaid) FROM ns_transactions t JOIN ns_open o ON o.id = t.id WHERE t.entity = e.id AND t.type = 'CustInvc' AND t.duedate < ns_today()), 0) AS overduebalance,
140
- COALESCE((SELECT SUM(u.unapplied) FROM ns_transactions t JOIN ns_unapplied u ON u.id = t.id WHERE t.entity = e.id AND t.type = 'CustDep'), 0) AS depositbalance,
147
+ + COALESCE((SELECT SUM(a.amount) FROM ns_applications a JOIN ns_transactions p ON p.id=a.payment JOIN ns_transactions d ON d.id=a.doc WHERE p.type='CustRfnd' AND p.entity=e.id AND p.currency=e.currency AND d.type<>'CustDep'),0), 2) AS balance,
148
+ ROUND(COALESCE((SELECT SUM(o.unpaid) FROM ns_transactions t JOIN ns_open o ON o.id = t.id WHERE t.entity = e.id AND t.type = 'CustInvc' AND t.duedate < ns_today()), 0), 2) AS overduebalance,
149
+ ROUND(COALESCE((SELECT SUM(u.unapplied) FROM ns_transactions t JOIN ns_unapplied u ON u.id = t.id WHERE t.entity = e.id AND t.type = 'CustDep'), 0), 2) AS depositbalance,
141
150
  COALESCE((SELECT SUM(ROUND(CASE WHEN l.quantity > 0 THEN MAX(0, l.quantity - l.quantitybilled) * l.amount / l.quantity ELSE 0 END, 2)) FROM ns_lines l JOIN ns_transactions t ON t.id = l."transaction"
142
151
  WHERE t.entity = e.id AND t.type = 'SalesOrd' AND COALESCE(t.status, '') NOT IN ('C', 'H') AND l.sublist = 'item' AND l.isclosed = 0), 0) AS unbilledorders
143
152
  FROM ns_entities e WHERE e.kind = 'customer';
144
153
  CREATE VIEW ns_q_vendor AS SELECT e.id, e.entityid, e.companyname, e.legalname, e.accountnumber, e.email, e.phone, e.fax, e.url, ${bool("e.isinactive")} AS isinactive,
145
154
  ${bool("e.is1099eligible")} AS is1099eligible, e.terms, e.subsidiary, e.currency, e.comments, e.externalid, e.datecreated, e.lastmodifieddate, e.extra,
146
- COALESCE((SELECT SUM(CASE i.role WHEN 'debt' THEN i.original ELSE -i.original END) FROM ns_item_original i WHERE i.side='payable' AND i.entity=e.id AND i.currency=e.currency),0)
147
- - COALESCE((SELECT SUM(t.total) FROM ns_transactions t WHERE t.type='VendPymt' AND t.entity=e.id AND t.currency=e.currency),0) AS balance
155
+ ROUND(COALESCE((SELECT SUM(CASE i.role WHEN 'debt' THEN i.original ELSE -i.original END) FROM ns_item_original i WHERE i.side='payable' AND i.entity=e.id AND i.currency=e.currency),0)
156
+ - COALESCE((SELECT SUM(t.total) FROM ns_transactions t WHERE t.type='VendPymt' AND t.entity=e.id AND t.currency=e.currency),0), 2) AS balance
148
157
  FROM ns_entities e WHERE e.kind = 'vendor';
149
158
  CREATE VIEW ns_q_contact AS SELECT e.id, e.entityid, e.firstname, e.lastname, e.title, e.email, e.phone, e.mobilephone, e.company, ${bool("e.isinactive")} AS isinactive,
150
159
  e.comments, e.subsidiary, e.externalid, e.datecreated, e.lastmodifieddate, e.extra FROM ns_entities e WHERE e.kind = 'contact';
@@ -185,23 +194,24 @@ CREATE VIEW ns_q_transaction AS SELECT t.id, t.tranid, t.trandate, t.type, t.rec
185
194
  t.currency, t.exchangerate, t.otherrefnum, t.externalid, t.datecreated AS createddate, t.lastmodifieddate, t.total AS foreigntotal, t.postingperiod, t.employee, t.salesrep, t.extra,
186
195
  ${bool('EXISTS (SELECT 1 FROM ns_gl g WHERE g."transaction" = t.id)')} AS posting, 'F' AS voided,
187
196
  CASE WHEN t.type IN ('CustInvc', 'VendBill') THEN o.unpaid END AS foreignamountunpaid,
188
- CASE WHEN t.type IN ('CustInvc', 'VendBill') THEN t.total - o.unpaid END AS foreignamountpaid,
197
+ CASE WHEN t.type IN ('CustInvc', 'VendBill') THEN ROUND(t.total - o.unpaid, 2) END AS foreignamountpaid,
189
198
  CASE WHEN t.type IN ('CustInvc', 'VendBill') AND o.unpaid > 0 AND t.duedate < ns_today()
190
199
  THEN CAST(julianday(ns_today()) - julianday(t.duedate) AS INTEGER) ELSE 0 END AS daysoverdue
191
200
  FROM ns_transactions t JOIN ns_open o ON o.id = t.id;
192
201
  -- One row per transaction for its main line (the AR/AP/bank side), then one per sublist line. Lines carry NetSuite's
193
- -- native signs: an invoice's main line is +total and its item lines are negative; a bill's are the reverse.
202
+ -- native signs: an invoice's main line is +total and its item lines are negative; a bill's are the reverse. foreignamount
203
+ -- is in the transaction's currency, netamount in the base currency at the transaction's exchange rate.
194
204
  CREATE VIEW ns_q_transactionline AS
195
205
  -- Reserve four digits for the line; transaction IDs up to 2000000000 stay below 2^53.
196
206
  SELECT 0 AS id, t.id * 10000 AS uniquekey, t.id AS "transaction", 0 AS linesequencenumber, 'T' AS mainline, 'F' AS taxline, NULL AS item, NULL AS itemtype, NULL AS quantity,
197
- NULL AS rate, ${signed("t.total", 0)} AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
207
+ NULL AS rate, ROUND(${signed("t.total", 0)} * t.exchangerate, 2) AS netamount, ${signed("t.total", 0)} AS foreignamount, t.memo, NULL AS expenseaccount, t.account, t.entity, t.subsidiary,
198
208
  t.department, t.location, t.class, t.createdfrom, 'F' AS isclosed,
199
209
  NULL AS debit, NULL AS credit, NULL AS quantitybilled, NULL AS quantityshiprecv, NULL AS quantitycommitted, NULL AS category, NULL AS costestimate, t.extra, 'F' AS iscogs
200
210
  FROM ns_transactions t WHERE t.type <> 'Journal'
201
211
  UNION ALL
202
212
  SELECT l.line AS id, l."transaction" * 10000 + l.line AS uniquekey, l."transaction", l.line, 'F', 'F', l.item, i.itemtype,
203
213
  ${signed("l.quantity", 2)}, l.rate,
204
- CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
214
+ ROUND(CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END * t.exchangerate, 2),
205
215
  CASE WHEN t.type = 'Journal' THEN COALESCE(l.debit, 0) - COALESCE(l.credit, 0) WHEN t.type IN ('ItemShip', 'ItemRcpt') THEN NULL ELSE ${signed("l.amount", 1)} END,
206
216
  COALESCE(l.memo, l.description), l.account, l.account, COALESCE(l.entity, t.entity), t.subsidiary, COALESCE(l.department, t.department),
207
217
  COALESCE(l.location, t.location), COALESCE(l.class, t.class), l.createdfrom, ${bool("l.isclosed")}, l.debit, l.credit,
@@ -211,7 +221,7 @@ CREATE VIEW ns_q_transactionline AS
211
221
  FROM ns_lines l JOIN ns_transactions t ON t.id = l."transaction" LEFT JOIN ns_items i ON i.id = l.item WHERE l.sublist <> 'apply'
212
222
  UNION ALL
213
223
  SELECT 5000 + l.line, t.id * 10000 + 5000 + l.line, t.id, 5000 + l.line, 'F', 'F', l.item, i.itemtype,
214
- ${signed("l.quantity", 2)}, NULL, (COALESCE(g.debit, 0) - COALESCE(g.credit, 0)) / t.exchangerate,
224
+ ${signed("l.quantity", 2)}, NULL, COALESCE(g.debit, 0) - COALESCE(g.credit, 0),
215
225
  (COALESCE(g.debit, 0) - COALESCE(g.credit, 0)) / t.exchangerate, COALESCE(l.memo, l.description), g.account, g.account,
216
226
  g.entity, t.subsidiary, g.department, g.location, g.class, l.createdfrom, 'F', g.debit / t.exchangerate, g.credit / t.exchangerate,
217
227
  NULL, NULL, NULL, NULL, l.cost, l.extra, 'T'
@@ -531,7 +541,115 @@ var CUSTOM_TABLES = {
531
541
  custitem: ["item"]
532
542
  };
533
543
  var ENTITY_KINDS = { customer: "customer", vendor: "vendor", contact: "contact", employee: "employee" };
534
- function suiteqlTables(fields) {
544
+ function readCatalog(db) {
545
+ if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'ns_fields'").get()) return { plain: [], fields: [] };
546
+ return {
547
+ plain: db.prepare("SELECT type FROM ns_record_types ORDER BY type").all().map((row) => row.type),
548
+ fields: db.prepare("SELECT recordtype, sublist, field, owner, kind, target FROM ns_fields ORDER BY recordtype, sublist, field").all()
549
+ };
550
+ }
551
+ function givenSql(json, field, kind) {
552
+ const path = `'$."${field}"'`;
553
+ if (kind === "boolean") return `CASE json_type(${json}, ${path}) WHEN 'true' THEN 'T' WHEN 'false' THEN 'F' END`;
554
+ const value = `CASE json_type(${json}, ${path}) WHEN 'object' THEN json_extract(${json}, '$."${field}".id') ELSE json_extract(${json}, ${path}) END`;
555
+ return kind === "ref" ? `CAST(${value} AS INTEGER)` : value;
556
+ }
557
+ var KIND_TYPES = { "": "text", text: "text", enum: "text", number: "number", boolean: "boolean", date: "date", datetime: "datetime", ref: "id" };
558
+ var TRANSACTION_TYPES = /* @__PURE__ */ new Set([
559
+ "estimate",
560
+ "salesOrder",
561
+ "itemFulfillment",
562
+ "invoice",
563
+ "cashSale",
564
+ "cashRefund",
565
+ "creditMemo",
566
+ "customerPayment",
567
+ "customerDeposit",
568
+ "depositApplication",
569
+ "customerRefund",
570
+ "returnAuthorization",
571
+ "purchaseOrder",
572
+ "itemReceipt",
573
+ "vendorBill",
574
+ "vendorCredit",
575
+ "vendorPayment",
576
+ "vendorReturnAuthorization",
577
+ "journalEntry",
578
+ "expenseReport"
579
+ ]);
580
+ var targetTable = (target) => /Item$/.test(target) ? "item" : TRANSACTION_TYPES.has(target) ? "transaction" : target.toLowerCase();
581
+ var keptTable = (field) => field.owner === "entity" ? field.recordtype : field.owner === "item" ? "item" : field.owner === "transaction" ? field.sublist ? "transactionline" : "transaction" : field.recordtype.toLowerCase();
582
+ function merge(a, b) {
583
+ const both = (x, y) => a === x && b === y || a === y && b === x;
584
+ return a === b || b === "" ? a : a === "" ? b : both("ref", "enum") ? "enum" : both("date", "datetime") ? "datetime" : both("ref", "number") ? "ref" : "text";
585
+ }
586
+ function keptTables(tables, catalog) {
587
+ const byName = new Map(tables.map((table) => [table.name, table]));
588
+ const lookups = [];
589
+ const lookup = (table, column, kind, json, field, from) => {
590
+ const name = `${table}.${column}`, id = givenSql(json, field, kind);
591
+ lookups.push({
592
+ name,
593
+ view: "ns_records",
594
+ display: "name",
595
+ columns: [col("id", KIND_TYPES[kind]), col("name", "text")],
596
+ source: `SELECT ${id} AS "id", MIN(json_extract(${json}, '$."${field}".refName')) AS "name" FROM ${from} AND json_type(${json}, '$."${field}"') = 'object' GROUP BY 1`
597
+ });
598
+ return name;
599
+ };
600
+ const reference = (field, kind, table, column, json, from) => {
601
+ if (kind !== "ref" && kind !== "enum") return {};
602
+ const target = field.target === null ? void 0 : targetTable(field.target);
603
+ return { ref: target !== void 0 && (byName.has(target) || catalog.plain.some((type) => type.toLowerCase() === target)) ? target : lookup(table, column, kind, json, field.field, from) };
604
+ };
605
+ const plainName = (field) => /^[A-Za-z][A-Za-z0-9_]*$/.test(field) ? field.toLowerCase() : void 0;
606
+ const kinds = (fields) => {
607
+ const merged = /* @__PURE__ */ new Map();
608
+ for (const field of fields) {
609
+ const prior = merged.get(field.field);
610
+ merged.set(field.field, prior ? { ...prior, kind: merge(prior.kind, field.kind), target: prior.target ?? field.target } : field);
611
+ }
612
+ return [...merged.values()];
613
+ };
614
+ const extended = tables.map((table) => {
615
+ const fields = kinds(catalog.fields.filter((field) => field.owner !== "" && keptTable(field) === table.name));
616
+ if (!fields.length) return table;
617
+ const columns = [...table.columns], names = new Set(columns.map((c) => c.name)), lines = table.name === "transactionline";
618
+ for (const field of fields) {
619
+ const name = plainName(field.field), type = KIND_TYPES[field.kind];
620
+ if (name === void 0 || type === void 0 || names.has(name)) continue;
621
+ names.add(name);
622
+ const json = lines ? "extra" : "x.fields";
623
+ const value = givenSql(json, field.field, field.kind);
624
+ const from = lines ? `${table.view} WHERE 1 = 1` : `ns_extra x WHERE x.owner = '${field.owner}'`;
625
+ columns.push(col(name, type, {
626
+ sql: lines ? value : `(SELECT ${value} FROM ns_extra x WHERE x.owner = '${field.owner}' AND x.id = "${table.view}"."id")`,
627
+ ...reference(field, field.kind, table.name, name, json, from)
628
+ }));
629
+ }
630
+ return { ...table, columns };
631
+ });
632
+ const plain = catalog.plain.map((type) => {
633
+ const name = type.toLowerCase(), columns = [col("id", "id"), col("externalid", "text")], selects = ['r.id AS "id"', 'r.externalid AS "externalid"'];
634
+ const names = /* @__PURE__ */ new Set(["id", "externalid"]), from = `ns_records r WHERE r.type = '${type}'`;
635
+ for (const field of kinds(catalog.fields.filter((f) => f.owner === "" && f.recordtype === type))) {
636
+ const column = plainName(field.field), kind = field.kind, nsType = KIND_TYPES[kind];
637
+ if (column === void 0 || nsType === void 0 || names.has(column)) continue;
638
+ names.add(column);
639
+ columns.push(col(column, nsType, reference(field, kind, name, column, "r.fields", from)));
640
+ selects.push(`${givenSql("r.fields", field.field, kind)} AS "${column}"`);
641
+ }
642
+ const display = ["name", "entityid", "companyname", "title", "tranid"].find((column) => names.has(column)) ?? "id";
643
+ return { name, view: "ns_records", display, columns, source: `SELECT ${selects.join(", ")} FROM ${from}` };
644
+ });
645
+ const replaced = new Set(plain.map((table) => table.name));
646
+ return [...extended.filter((table) => !replaced.has(table.name)), ...plain, ...lookups];
647
+ }
648
+ function suiteqlTables(fields, catalog) {
649
+ const custom = customTables(fields);
650
+ return catalog && (catalog.plain.length || catalog.fields.length) ? keptTables(custom, catalog) : custom;
651
+ }
652
+ function customTables(fields) {
535
653
  if (!fields.length) return SUITEQL_TABLES;
536
654
  return SUITEQL_TABLES.map((table) => {
537
655
  const extra = fields.filter((f) => {
@@ -1419,7 +1537,7 @@ var Compiler = class {
1419
1537
  const table = this.tables.find((t) => t.name === source.table);
1420
1538
  if (!table) invalid(`Record '${source.table}' was not found.`);
1421
1539
  const computed = table.columns.filter((c) => c.sql);
1422
- value = computed.length ? sql("(SELECT *, ", computed.map((c) => `${c.sql} AS ${quote(c.name)}`).join(", "), " FROM ", quote(table.view), ")") : sql(quote(table.view));
1540
+ value = table.source ? sql("(", table.source, ")") : computed.length ? sql("(SELECT *, ", computed.map((c) => `${c.sql} AS ${quote(c.name)}`).join(", "), " FROM ", quote(table.view), ")") : sql(quote(table.view));
1423
1541
  columns = table.columns.map((column) => ({ name: column.name, type: column.type, value: sql(""), origin: { table, column, relation: alias } }));
1424
1542
  }
1425
1543
  columns = columns.map((c) => ({ ...c, value: sql(`${quote(alias)}.${quote(c.name)}`) }));
@@ -1724,7 +1842,7 @@ var Compiler = class {
1724
1842
  if (!mode || !modes.includes(mode)) invalid("BUILTIN.HIERARCHY requires a valid expansion type literal.");
1725
1843
  const table = origin && this.tables.find((t) => t.name === (origin.column.ref ?? (origin.column.name === "id" ? origin.table.name : "")));
1726
1844
  const parent = table?.columns.find((c) => c.name === "parent" || c.name === "supervisor");
1727
- if (!table || !parent) invalid("BUILTIN.HIERARCHY requires a hierarchical field.");
1845
+ if (!table || !parent || table.source) invalid("BUILTIN.HIERARCHY requires a hierarchical field.");
1728
1846
  return bound(sql("ns_suiteql_hierarchy(", param(table.view), ", ", param(parent.name), ", ", param(table.display), ", ", a, ", ", args[1], ")"), mode === "LEVEL" ? "integer" : "text", args);
1729
1847
  }
1730
1848
  case "builtin.df": {
@@ -1734,7 +1852,7 @@ var Compiler = class {
1734
1852
  const table = this.tables.find((t) => t.name === origin.column.ref);
1735
1853
  if (!table) invalid("BUILTIN.DF requires a reference or coded column.");
1736
1854
  const alias = "sq_display";
1737
- return bound(sql("(SELECT ", `${quote(alias)}.${quote(table.display)}`, " FROM ", quote(table.view), " AS ", quote(alias), " WHERE ", `${quote(alias)}."id" = `, a, ")"), "text", args);
1855
+ return bound(sql("(SELECT ", `${quote(alias)}.${quote(table.display)}`, " FROM ", table.source ? `(${table.source})` : quote(table.view), " AS ", quote(alias), " WHERE ", `${quote(alias)}."id" = `, a, ")"), "text", args);
1738
1856
  }
1739
1857
  if (origin.column.display) {
1740
1858
  return bound(sql("(CASE ", a, ...Object.entries(DISPLAY[origin.column.display]).map(([k, v]) => sql(" WHEN ", param(k), " THEN ", param(v))), " ELSE NULL END)"), "text", args);
@@ -1833,7 +1951,7 @@ var Compiler = class {
1833
1951
  function compileSuiteql(query, opts) {
1834
1952
  const values = (opts.params ?? []).map(bindValue), parser = new Parser(query), parsed = parser.parse();
1835
1953
  if (parser.markers !== values.length) invalid(`The query has ${parser.markers} ? marker${parser.markers === 1 ? "" : "s"} and ${values.length} params value${values.length === 1 ? "" : "s"}.`);
1836
- const result = new Compiler({ today: opts.today, now: opts.now, tables: suiteqlTables(opts.customFields ?? []), values }).query(parsed, void 0, MAX_RESULTS);
1954
+ const result = new Compiler({ today: opts.today, now: opts.now, tables: suiteqlTables(opts.customFields ?? [], opts.catalog), values }).query(parsed, void 0, MAX_RESULTS);
1837
1955
  return { sql: result.sql, params: result.params, columns: result.columns.map((c) => ({ name: c.name, type: c.type === "null" ? "text" : c.type })) };
1838
1956
  }
1839
1957
  function bindValue(value) {
@@ -2454,7 +2572,7 @@ function runSuiteqlMapped(db, query, page, opts) {
2454
2572
  function scan(db, query, page, opts) {
2455
2573
  if (!Number.isSafeInteger(page.limit) || page.limit < 0 || !Number.isSafeInteger(page.offset) || page.offset < 0) invalid("Invalid paging values.");
2456
2574
  if (page.offset >= MAX_RESULTS) invalid("Offset must be less than the 100000 result limit.");
2457
- const compiled = compileSuiteql(query, opts);
2575
+ const compiled = compileSuiteql(query, { ...opts, catalog: opts.catalog ?? readCatalog(db) });
2458
2576
  installFunctions(db, compiled.sql.includes("ns_suiteql_hierarchy("));
2459
2577
  try {
2460
2578
  return db.transaction(() => {