@memberjunction/generic-database-provider 6.2.0-edge.1 → 6.2.0-edge.3

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.
@@ -15,15 +15,15 @@
15
15
  *
16
16
  * @module @memberjunction/generic-database-provider
17
17
  */
18
- import { DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
19
- import { MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
18
+ import { SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
19
+ import { BytesToBase64, IsByteArray, MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
20
20
  import { QueryPagingEngine } from './queryPagingEngine.js';
21
21
  // QueryParameterProcessor is now called internally by RenderPipeline
22
22
  import { createHash } from 'node:crypto';
23
23
  import { v4 as uuidv4 } from 'uuid';
24
24
  import { SqlLoggingSessionImpl } from './SqlLogger.js';
25
25
  import { GetDialect } from '@memberjunction/sql-dialect';
26
- import { SQLParser } from '@memberjunction/sql-parser';
26
+ import { SQLParser, IsReadOnlyQuery } from '@memberjunction/sql-parser';
27
27
  // QueryCompositionEngine is now owned by RenderPipeline
28
28
  import { RenderPipeline } from './renderPipeline.js';
29
29
  import { UseJsonArgShape } from './crudSprocFieldRules.js';
@@ -34,8 +34,14 @@ import { QueueManager } from '@memberjunction/queue';
34
34
  import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
35
35
  import { BuildEntityChangeContext } from '@memberjunction/actions-base';
36
36
  import { TransactionFrameTracker } from './TransactionFrameTracker.js';
37
+ import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
37
38
  import { EncryptionEngine } from '@memberjunction/encryption';
38
39
  import { GeoCodeSyncService } from '@memberjunction/geo-core';
40
+ /**
41
+ * Execution options for SQL a caller supplied rather than a saved query (ad-hoc SQL, transient test
42
+ * queries): run it read-only and roll back, so it can neither write nor leave session state behind.
43
+ */
44
+ const CALLER_SQL_OPTIONS = { readOnlyTransaction: true, description: 'caller-supplied query' };
39
45
  /**
40
46
  * GenericDatabaseProvider is an intermediate abstract class that implements shared
41
47
  * entity action, AI action, encryption, and view WHERE clause rendering logic.
@@ -553,7 +559,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
553
559
  // No explicit connectionSource: sibling writes must land in the same transaction as the
554
560
  // save that triggered them, which is what happens by default — ExecuteSQL runs on the
555
561
  // provider's ambient transaction when no source is given.
556
- ? this.PropagateRecordChangesToSiblings(entity.EntityInfo, overlappingChangeData, entity.PrimaryKey.Values(), user?.ID ?? '', options.ISAActiveChildEntityName)
562
+ ? this.PropagateRecordChangesToSiblings(entity.EntityInfo, overlappingChangeData, entity.PrimaryKey.Values(), user?.ID ?? '', options.ISAActiveChildEntityName, undefined, entity.CloneContext ? 'Clone' : 'Internal', entity.CloneContext ? SerializeCloneChangeContext(entity.CloneContext) : null)
557
563
  : null;
558
564
  // Await both in parallel
559
565
  if (geoPromise && siblingPromise) {
@@ -634,6 +640,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
634
640
  async PostProcessRows(rows, entityInfo, user) {
635
641
  if (!rows || rows.length === 0)
636
642
  return rows;
643
+ // Step 0: binary columns → base64. Drivers return varbinary/bytea as byte arrays (Node
644
+ // Buffers); BaseEntity, the caches and every transport hold binary values as base64
645
+ // strings, so the conversion happens once, here, for every row a provider returns.
646
+ // Applies to external entities too — their drivers return Buffers just the same.
647
+ this.ConvertBinaryFieldsToBase64(rows, entityInfo.BinaryFields);
637
648
  // Step 1: Platform-specific datetime adjustment (virtual hook).
638
649
  // SKIP for external entities: AdjustDatetimeFields applies THIS provider's platform correction
639
650
  // (e.g. SQL Server appends 'Z' to compensate for how tedious marshals datetimes from the LOCAL
@@ -672,6 +683,65 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
672
683
  return processedRow;
673
684
  }));
674
685
  }
686
+ /**
687
+ * Public entry point to {@link PostProcessRows} for code that runs SQL outside the provider's
688
+ * own read paths but returns entity rows — the transaction groups. Every row a provider hands
689
+ * back must pass through here, so binary columns become base64, datetimes are adjusted and
690
+ * encrypted fields are decrypted no matter which path saved the record.
691
+ *
692
+ * @param rows - Raw rows for `entityInfo`.
693
+ * @param entityInfo - The entity the rows belong to.
694
+ * @param contextUser - The user the rows are processed for (decryption runs as this user).
695
+ * @returns The processed rows.
696
+ */
697
+ async ProcessEntityRows(rows, entityInfo, contextUser) {
698
+ if (!rows || rows.length === 0)
699
+ return rows;
700
+ return this.PostProcessRows(rows, entityInfo, contextUser);
701
+ }
702
+ /**
703
+ * Converts the byte-array values of an entity's binary fields to base64 strings, in place.
704
+ *
705
+ * Database drivers return `varbinary` / `binary` / `image` (SQL Server) and `bytea`
706
+ * (PostgreSQL) columns as `Uint8Array`s (Node `Buffer`s). MemberJunction's representation of
707
+ * a binary value above the provider is a base64 string, so it is JSON-safe for dirty tracking,
708
+ * Record Changes, the RunView caches and every transport. Values that are already strings,
709
+ * null or absent are left untouched, which makes the conversion idempotent.
710
+ *
711
+ * @param rows - Rows as returned by the driver; mutated in place.
712
+ * @param binaryFields - The entity's binary fields (`EntityInfo.BinaryFields`).
713
+ */
714
+ ConvertBinaryFieldsToBase64(rows, binaryFields) {
715
+ if (binaryFields.length === 0)
716
+ return;
717
+ for (const row of rows) {
718
+ for (const field of binaryFields) {
719
+ const value = row[field.Name];
720
+ if (IsByteArray(value))
721
+ row[field.Name] = BytesToBase64(value);
722
+ }
723
+ }
724
+ }
725
+ /**
726
+ * Converts every byte-array value in a set of rows to a base64 string, in place. For results
727
+ * with no entity metadata, such as RunQuery and ad-hoc SQL, where binary columns can only be
728
+ * recognised by value. See {@link ConvertBinaryFieldsToBase64}.
729
+ *
730
+ * @param rows - Rows as returned by the driver; mutated in place.
731
+ */
732
+ ConvertByteArrayValuesToBase64(rows) {
733
+ if (!rows)
734
+ return;
735
+ for (const row of rows) {
736
+ if (!row || typeof row !== 'object')
737
+ continue;
738
+ for (const key of Object.keys(row)) {
739
+ const value = row[key];
740
+ if (IsByteArray(value))
741
+ row[key] = BytesToBase64(value);
742
+ }
743
+ }
744
+ }
675
745
  /**************************************************************************/
676
746
  // PreProcessFieldsForSave — Field-Level Encryption Before Save
677
747
  /**************************************************************************/
@@ -1039,7 +1109,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1039
1109
  };
1040
1110
  }
1041
1111
  }
1042
- const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'");
1112
+ const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext);
1043
1113
  if (payload) {
1044
1114
  saveSQL = this.WrapSaveCallWithRecordChange(saveSQL, binding, payload, entity);
1045
1115
  }
@@ -1353,6 +1423,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1353
1423
  * aggregates, parallel query execution, post-processing, and audit logging.
1354
1424
  */
1355
1425
  async InternalRunView(params, contextUser) {
1426
+ return this.RunViewCore(params, contextUser);
1427
+ }
1428
+ /**
1429
+ * The body of {@link InternalRunView}. `countExecutor`, when supplied, replaces the
1430
+ * direct execution of a `count_only` view's COUNT query — {@link InternalRunViews} uses
1431
+ * it to coalesce an all-`count_only` batch into one statement (see countOnlyBatch.ts).
1432
+ * Everything before that step — permissions, RLS, filter screening — is unchanged.
1433
+ */
1434
+ async RunViewCore(params, contextUser, countExecutor) {
1356
1435
  if (params?.Aggregates?.length) {
1357
1436
  LogStatus(`[GenericDatabaseProvider] InternalRunView received aggregates: entityName=${params.EntityName}, viewID=${params.ViewID}, viewName=${params.ViewName}, aggregateCount=${params.Aggregates.length}`);
1358
1437
  }
@@ -1674,7 +1753,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1674
1753
  const maxRowsUsed = params.MaxRows || entityInfo.UserViewMaxRows;
1675
1754
  const willNeedCount = countSQL && (usingPagination || params.ResultType === 'count_only');
1676
1755
  if (willNeedCount) {
1677
- queries.push(this.ExecuteSQL(countSQL, undefined, undefined, contextUser));
1756
+ queries.push(countExecutor && params.ResultType === 'count_only'
1757
+ ? countExecutor(countSQL)
1758
+ : this.ExecuteSQL(countSQL, undefined, undefined, contextUser));
1678
1759
  queryKeys.push('count');
1679
1760
  }
1680
1761
  const aggregateStartTime = Date.now();
@@ -1771,9 +1852,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1771
1852
  }
1772
1853
  }
1773
1854
  async InternalRunViews(params, contextUser) {
1855
+ if (IsCoalescibleCountBatch(params)) {
1856
+ return this.RunCoalescedCountBatch(params, contextUser);
1857
+ }
1774
1858
  const promises = params.map((p) => this.InternalRunView(p, contextUser));
1775
1859
  return Promise.all(promises);
1776
1860
  }
1861
+ /**
1862
+ * All-`count_only` batch: every view runs the normal per-view path (so every
1863
+ * security gate applies per view), but their COUNT queries are executed as ONE
1864
+ * `UNION ALL` statement — one database round trip for, e.g., every related-section
1865
+ * badge on a form. A view that fails keeps its own `Success:false` result; a connection
1866
+ * failure is thrown, as on the per-view path.
1867
+ */
1868
+ async RunCoalescedCountBatch(params, contextUser) {
1869
+ const batch = new CountOnlyBatchCoalescer(params.length, (sql) => this.ExecuteSQL(sql, undefined, undefined, contextUser), (name) => this.QuoteIdentifier(name), (error) => this.isConnectionError(error));
1870
+ return Promise.all(params.map((p, index) => this.RunViewCore(p, contextUser, (countSQL) => batch.Execute(index, countSQL))
1871
+ .finally(() => batch.MarkSettled(index))));
1872
+ }
1777
1873
  /**************************************************************************/
1778
1874
  // InternalRunView Helpers
1779
1875
  /**************************************************************************/
@@ -1843,6 +1939,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1843
1939
  if (!entityInfo)
1844
1940
  throw new Error(`Entity ${params.EntityName} not found in metadata`);
1845
1941
  }
1942
+ // Binary columns are omitted from every implicit field list (saved-view columns and
1943
+ // the no-Fields wildcard) unless requested; an explicit params.Fields entry is honoured.
1944
+ const includeBinary = params.IncludeBinaryFields === true;
1846
1945
  const flsUser = contextUser ?? this.CurrentUser;
1847
1946
  const denied = params.ResultType !== 'entity_object' && flsUser && entityInfo.EnableFieldLevelSecurity
1848
1947
  ? entityInfo.GetDeniedReadFields(flsUser)
@@ -1868,6 +1967,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1868
1967
  if (c.EntityField) {
1869
1968
  if (denied.has(c.EntityField.Name.trim().toLowerCase()))
1870
1969
  return; // silent narrowing
1970
+ if (!includeBinary && c.EntityField.IsBinaryFieldType)
1971
+ return; // binary only on request
1871
1972
  fieldList.push(c.EntityField);
1872
1973
  }
1873
1974
  else {
@@ -1880,13 +1981,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1880
1981
  fieldList.push(ef);
1881
1982
  }
1882
1983
  }
1883
- else if (denied.size > 0) {
1884
- // No explicit fields and no saved view would emit `SELECT *` — for a restricted
1885
- // user that pulls denied columns out of the database, so emit the explicit
1886
- // allowed-column list instead (PKs are unrestrictable and always included).
1984
+ else if (denied.size > 0 || (entityInfo.HasBinaryFields && !includeBinary)) {
1985
+ // No explicit fields and no saved view would emit `SELECT *`. For a restricted
1986
+ // user that pulls denied columns out of the database, and for an entity with
1987
+ // binary columns it pulls large values nobody asked for — so emit the explicit
1988
+ // column list instead (PKs are unrestrictable and always included).
1887
1989
  for (const ef of entityInfo.Fields) {
1888
- if (!denied.has(ef.Name.trim().toLowerCase()))
1889
- fieldList.push(ef);
1990
+ if (denied.has(ef.Name.trim().toLowerCase()))
1991
+ continue;
1992
+ if (!includeBinary && ef.IsBinaryFieldType && !ef.IsPrimaryKey)
1993
+ continue;
1994
+ fieldList.push(ef);
1890
1995
  }
1891
1996
  }
1892
1997
  }
@@ -2268,7 +2373,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2268
2373
  // ALL fields, for every user: server slots are full-width and shared, and
2269
2374
  // field security narrows per request at read time via
2270
2375
  // ApplyFieldSecurityProjection rather than at fetch time.
2271
- p.Fields = this.ComputeRunViewFetchFields(widenEntity);
2376
+ this.ResolveIncludeBinaryFields(p, widenEntity);
2377
+ p.Fields = this.ComputeRunViewFetchFields(widenEntity, p);
2272
2378
  if (requested) {
2273
2379
  callerFieldsByIndex.set(i, ProviderBase.UnionFieldsWithPrimaryKeys(requested, widenEntity));
2274
2380
  }
@@ -3521,6 +3627,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3521
3627
  ]);
3522
3628
  matExecutionTime = Date.now() - start;
3523
3629
  rows = dataResult ?? [];
3630
+ this.ConvertByteArrayValuesToBase64(rows);
3524
3631
  matTotalRowCount = countResult?.[0]?.TotalRowCount != null ? Number(countResult[0].TotalRowCount) : rows.length;
3525
3632
  }
3526
3633
  else {
@@ -3601,6 +3708,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3601
3708
  if (!dataResult)
3602
3709
  throw new Error('Error executing paged query SQL');
3603
3710
  paginatedResult = dataResult;
3711
+ this.ConvertByteArrayValuesToBase64(paginatedResult);
3604
3712
  totalRowCount = countResult?.[0]?.TotalRowCount != null
3605
3713
  ? Number(countResult[0].TotalRowCount)
3606
3714
  : paginatedResult.length;
@@ -3683,7 +3791,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3683
3791
  try {
3684
3792
  const validator = SQLExpressionValidator.Instance;
3685
3793
  const validation = validator.validateFullQuery(params.SQL);
3686
- if (!validation.valid) {
3794
+ const statementCheck = IsReadOnlyQuery(params.SQL, this.Dialect);
3795
+ if (!validation.valid || !statementCheck.IsReadOnly) {
3687
3796
  return {
3688
3797
  Success: false,
3689
3798
  QueryID: '',
@@ -3692,17 +3801,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3692
3801
  RowCount: 0,
3693
3802
  TotalRowCount: 0,
3694
3803
  ExecutionTime: 0,
3695
- ErrorMessage: validation.error || 'SQL validation failed',
3804
+ ErrorMessage: !validation.valid
3805
+ ? validation.error || 'SQL validation failed'
3806
+ : `Ad-hoc SQL must be a single read query: ${statementCheck.Reason}.`,
3696
3807
  };
3697
3808
  }
3698
- const { result, executionTime } = await this.executeQueryWithTiming(params.SQL, contextUser);
3699
- const { paginatedResult, totalRowCount } = this.applyQueryPagination(result, params);
3809
+ const { rows, totalRowCount, executionTime } = await this.runAdhocSQL(params, contextUser);
3700
3810
  return {
3701
3811
  Success: true,
3702
3812
  QueryID: '',
3703
3813
  QueryName: 'Ad-Hoc Query',
3704
- Results: paginatedResult,
3705
- RowCount: paginatedResult.length,
3814
+ Results: rows,
3815
+ RowCount: rows.length,
3706
3816
  TotalRowCount: totalRowCount,
3707
3817
  ExecutionTime: executionTime,
3708
3818
  ErrorMessage: '',
@@ -3723,6 +3833,60 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3723
3833
  };
3724
3834
  }
3725
3835
  }
3836
+ /**
3837
+ * Runs validated ad-hoc SQL. It is rendered the way caller-supplied SQL always is: composition
3838
+ * tokens resolved, comments removed, and a single read query required. With `MaxRows` the
3839
+ * database returns that page and a count runs beside it, as for saved queries, so the server
3840
+ * sends one page rather than every row; without it every row is returned, offset by `StartRow`
3841
+ * when one is given. `TimeoutSeconds` limits every statement the run sends.
3842
+ */
3843
+ async runAdhocSQL(params, contextUser) {
3844
+ const usePaging = QueryPagingEngine.ShouldPage(params.StartRow, params.MaxRows);
3845
+ const startRow = QueryPagingEngine.ResolveStartRow(params.StartRow);
3846
+ const rendered = RenderPipeline.Run(params.SQL, {
3847
+ Platform: this.PlatformKey,
3848
+ ContextUser: contextUser,
3849
+ RequireReadStatement: true,
3850
+ ...(usePaging ? { Paging: { StartRow: startRow, MaxRows: params.MaxRows } } : {}),
3851
+ });
3852
+ const options = this.adhocSQLOptions(params);
3853
+ if (!usePaging) {
3854
+ const { result, executionTime } = await this.executeQueryWithTiming(rendered.FinalSQL, contextUser, undefined, options);
3855
+ const { paginatedResult, totalRowCount } = this.applyQueryPagination(result, params);
3856
+ return { rows: paginatedResult, totalRowCount, executionTime };
3857
+ }
3858
+ const start = Date.now();
3859
+ const [dataResult, total] = await Promise.all([
3860
+ this.ExecuteSQL(rendered.FinalSQL, undefined, options, contextUser),
3861
+ this.countAdhocRows(rendered.PagingResult?.CountSQL ?? null, options, contextUser),
3862
+ ]);
3863
+ const rows = dataResult ?? [];
3864
+ return { rows, totalRowCount: total ?? startRow + rows.length, executionTime: Date.now() - start };
3865
+ }
3866
+ /**
3867
+ * The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
3868
+ * fails does not fail the run: some queries page fine but cannot be counted (duplicate column
3869
+ * names are legal in a result but not inside the count's wrap), so the caller reports a lower
3870
+ * bound instead.
3871
+ */
3872
+ async countAdhocRows(countSQL, options, contextUser) {
3873
+ if (!countSQL)
3874
+ return null;
3875
+ try {
3876
+ const countResult = await this.ExecuteSQL(countSQL, undefined, options, contextUser);
3877
+ const total = Number(countResult?.[0]?.TotalRowCount);
3878
+ return Number.isFinite(total) && total >= 0 ? Math.floor(total) : null;
3879
+ }
3880
+ catch (e) {
3881
+ LogError(`Ad-hoc query row count failed; reporting a lower-bound total. ${e instanceof Error ? e.message : String(e)}`);
3882
+ return null;
3883
+ }
3884
+ }
3885
+ /** The options every statement of an ad-hoc run uses: caller-SQL protections, plus its timeout. */
3886
+ adhocSQLOptions(params) {
3887
+ const seconds = params.TimeoutSeconds;
3888
+ return seconds && seconds > 0 ? { ...CALLER_SQL_OPTIONS, timeoutMs: seconds * 1000 } : CALLER_SQL_OPTIONS;
3889
+ }
3726
3890
  /**
3727
3891
  * Finds a query from RunQueryParams and validates user permissions.
3728
3892
  * Uses `resolveQuery()` for lookup and `ValidateQueryForExecution()` for permissions.
@@ -3889,7 +4053,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3889
4053
  const resolved = this.resolveSpecParameters(spec, contextUser);
3890
4054
  finalSQL = resolved.finalSQL;
3891
4055
  // Execute
3892
- const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser);
4056
+ const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser, undefined, CALLER_SQL_OPTIONS);
3893
4057
  return {
3894
4058
  Success: true,
3895
4059
  QueryID: '',
@@ -3939,6 +4103,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3939
4103
  Dependencies: spec.Dependencies,
3940
4104
  OriginalSQL: spec.SQL,
3941
4105
  MaxRows: spec.MaxRows,
4106
+ RequireReadStatement: true,
3942
4107
  });
3943
4108
  if (!result.HasCompositions && !spec.UsesTemplate && spec.Parameters && Object.keys(spec.Parameters).length > 0) {
3944
4109
  LogStatus('Warning: Parameters provided but query does not use templates. Parameters will be ignored.');
@@ -3964,13 +4129,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3964
4129
  /**
3965
4130
  * Executes the query SQL and tracks execution time.
3966
4131
  */
3967
- async executeQueryWithTiming(sql, contextUser, parameters) {
4132
+ async executeQueryWithTiming(sql, contextUser, parameters, options) {
3968
4133
  const start = Date.now();
3969
- const result = await this.ExecuteSQL(sql, parameters, undefined, contextUser);
4134
+ const result = await this.ExecuteSQL(sql, parameters, options, contextUser);
3970
4135
  const executionTime = Date.now() - start;
3971
4136
  if (!result) {
3972
4137
  throw new Error('Error executing query SQL');
3973
4138
  }
4139
+ // Query results carry no entity metadata, so binary columns are found by value.
4140
+ this.ConvertByteArrayValuesToBase64(result);
3974
4141
  return { result, executionTime };
3975
4142
  }
3976
4143
  /**
@@ -4385,9 +4552,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4385
4552
  * work, so it must never land on a transaction's connection beside its COMMIT (#4514). Every
4386
4553
  * other dataset keeps joining the ambient transaction: a caller that writes and then loads a
4387
4554
  * dataset inside one transaction expects to see its own rows.
4555
+ *
4556
+ * {@link ProviderBase.RefreshWithinTransaction} is the exception: the caller owns the
4557
+ * transaction and is waiting for the reload, so the metadata reads join that transaction and
4558
+ * see the caller's uncommitted rows (MJ#4836).
4388
4559
  */
4389
4560
  datasetReadsOnPool(datasetName) {
4390
- return datasetName === GenericDatabaseProvider._mjMetadataDatasetName;
4561
+ return datasetName === GenericDatabaseProvider._mjMetadataDatasetName
4562
+ && !this.MetadataReadsJoinTransaction;
4391
4563
  }
4392
4564
  /**
4393
4565
  * Builds a parameter placeholder for parameterized queries.
@@ -4560,6 +4732,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4560
4732
  continue;
4561
4733
  }
4562
4734
  let itemData = batchResults[i] || [];
4735
+ // Binary columns become base64 whether or not the entity post-processing below runs —
4736
+ // at boot there is no context user, and a raw Buffer must never reach the metadata
4737
+ // cache or the wire (it serializes as {"type":"Buffer","data":[...]}).
4738
+ this.ConvertByteArrayValuesToBase64(itemData);
4563
4739
  // Post-process rows for encryption/datetime
4564
4740
  if (itemData.length > 0) {
4565
4741
  const entityInfo = provider.EntityByName(entityName);
@@ -4653,7 +4829,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4653
4829
  `INNER JOIN ${provider.QuoteSchemaAndView(schema, 'vwDatasetItems')} di ON d.${provider.QuoteIdentifier('ID')} = di.${provider.QuoteIdentifier('DatasetID')} ` +
4654
4830
  `INNER JOIN ${provider.QuoteSchemaAndView(schema, 'vwEntities')} e ON di.${provider.QuoteIdentifier('EntityID')} = e.${provider.QuoteIdentifier('ID')} ` +
4655
4831
  `WHERE d.${provider.QuoteIdentifier('Name')} = ${provider.BuildParameterPlaceholder(0)}`;
4656
- const items = await provider.ExecuteSQL(sSQL, [datasetName], { ignoreAmbientTransaction: this.datasetReadsOnPool(datasetName) }, contextUser);
4832
+ const readOptions = { ignoreAmbientTransaction: this.datasetReadsOnPool(datasetName) };
4833
+ const items = await provider.ExecuteSQL(sSQL, [datasetName], readOptions, contextUser);
4657
4834
  if (!items || items.length === 0) {
4658
4835
  return {
4659
4836
  DatasetID: '',
@@ -4712,7 +4889,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4712
4889
  });
4713
4890
  let batchResults = [];
4714
4891
  try {
4715
- batchResults = await provider.ExecuteSQLBatch(queries, undefined, undefined, contextUser);
4892
+ batchResults = await provider.ExecuteSQLBatch(queries, undefined, { ignoreAmbientTransaction: readOptions.ignoreAmbientTransaction }, contextUser);
4716
4893
  }
4717
4894
  catch (err) {
4718
4895
  LogError(`GetDatasetStatusByName: Batch execution failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -4763,9 +4940,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4763
4940
  /**
4764
4941
  * Validates columns for a dataset item and returns the column list string.
4765
4942
  * Returns null if columns are invalid.
4943
+ *
4944
+ * An item that names no columns selects every column EXCEPT binary ones, matching RunView's
4945
+ * default (binary columns are large and rarely wanted; see guides/BINARY_FIELDS_GUIDE.md). A
4946
+ * binary column can still be named explicitly. When the entity's metadata is not loaded yet —
4947
+ * the first `MJ_Metadata` read at boot — the item falls back to `*`, and the rows' byte arrays
4948
+ * are converted to base64 by the caller.
4766
4949
  */
4767
4950
  getColumnsForDatasetItem(item, datasetName) {
4768
4951
  const specifiedColumns = item['Columns'] ? String(item['Columns']).split(',').map(col => col.trim()) : [];
4952
+ if (specifiedColumns.length === 0) {
4953
+ const entity = this.EntityByID(item['EntityID']);
4954
+ if (entity?.HasBinaryFields) {
4955
+ return entity.Fields.filter(f => !f.IsBinaryFieldType).map(f => this.QuoteIdentifier(f.Name)).join(',');
4956
+ }
4957
+ }
4769
4958
  if (specifiedColumns.length > 0) {
4770
4959
  const entity = this.EntityByID(item['EntityID']);
4771
4960
  if (!entity && this.Entities.length > 0) {