@powersync/service-module-mssql 0.0.0-dev-20260602073133 → 0.0.0-dev-20260909133214

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +209 -4
  2. package/dist/api/MSSQLRouteAPIAdapter.d.ts +4 -5
  3. package/dist/api/MSSQLRouteAPIAdapter.js +33 -39
  4. package/dist/api/MSSQLRouteAPIAdapter.js.map +1 -1
  5. package/dist/common/MSSQLSourceTable.d.ts +12 -2
  6. package/dist/common/MSSQLSourceTable.js +30 -4
  7. package/dist/common/MSSQLSourceTable.js.map +1 -1
  8. package/dist/module/MSSQLModule.js +2 -1
  9. package/dist/module/MSSQLModule.js.map +1 -1
  10. package/dist/replication/CDCPoller.d.ts +13 -36
  11. package/dist/replication/CDCPoller.js +173 -129
  12. package/dist/replication/CDCPoller.js.map +1 -1
  13. package/dist/replication/CDCReplicationJob.js +1 -1
  14. package/dist/replication/CDCReplicationJob.js.map +1 -1
  15. package/dist/replication/CDCReplicator.js +1 -1
  16. package/dist/replication/CDCReplicator.js.map +1 -1
  17. package/dist/replication/CDCStream.d.ts +11 -14
  18. package/dist/replication/CDCStream.js +124 -115
  19. package/dist/replication/CDCStream.js.map +1 -1
  20. package/dist/replication/CaptureReconciler.d.ts +47 -0
  21. package/dist/replication/CaptureReconciler.js +155 -0
  22. package/dist/replication/CaptureReconciler.js.map +1 -0
  23. package/dist/replication/MSSQLConnectionManager.d.ts +1 -0
  24. package/dist/replication/MSSQLConnectionManager.js +19 -14
  25. package/dist/replication/MSSQLConnectionManager.js.map +1 -1
  26. package/dist/replication/MSSQLTableReconciliationContext.d.ts +21 -0
  27. package/dist/replication/MSSQLTableReconciliationContext.js +7 -0
  28. package/dist/replication/MSSQLTableReconciliationContext.js.map +1 -0
  29. package/dist/replication/SchemaChange.d.ts +67 -0
  30. package/dist/replication/SchemaChange.js +31 -0
  31. package/dist/replication/SchemaChange.js.map +1 -0
  32. package/dist/types/types.d.ts +13 -0
  33. package/dist/types/types.js +28 -2
  34. package/dist/types/types.js.map +1 -1
  35. package/dist/utils/mssql.js +1 -1
  36. package/dist/utils/schema.d.ts +14 -1
  37. package/dist/utils/schema.js +43 -45
  38. package/dist/utils/schema.js.map +1 -1
  39. package/package.json +11 -21
  40. package/src/api/MSSQLRouteAPIAdapter.ts +38 -49
  41. package/src/common/MSSQLSourceTable.ts +32 -4
  42. package/src/module/MSSQLModule.ts +2 -1
  43. package/src/replication/CDCPoller.ts +206 -162
  44. package/src/replication/CDCReplicationJob.ts +1 -1
  45. package/src/replication/CDCReplicator.ts +1 -1
  46. package/src/replication/CDCStream.ts +157 -163
  47. package/src/replication/CaptureReconciler.ts +186 -0
  48. package/src/replication/MSSQLConnectionManager.ts +23 -14
  49. package/src/replication/MSSQLTableReconciliationContext.ts +29 -0
  50. package/src/replication/SchemaChange.ts +79 -0
  51. package/src/types/types.ts +47 -2
  52. package/src/utils/mssql.ts +1 -1
  53. package/src/utils/schema.ts +60 -54
  54. package/test/src/CDCPoller.test.ts +382 -0
  55. package/test/src/CDCStream.test.ts +6 -2
  56. package/test/src/CDCStreamTestContext.ts +30 -23
  57. package/test/src/CaptureReconciler.test.ts +171 -0
  58. package/test/src/MSSQLSourceTable.test.ts +30 -0
  59. package/test/src/config.test.ts +71 -0
  60. package/test/src/schema-changes.test.ts +513 -249
  61. package/test/src/schema.test.ts +17 -0
  62. package/test/src/util.ts +73 -9
  63. package/tsconfig.json +0 -3
  64. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,186 @@
1
+ import { ErrorCode, ReplicationAssertionError, ServiceError } from '@powersync/lib-services-framework';
2
+ import { JsonValue, SourceTableCandidate, storage } from '@powersync/service-core';
3
+ import * as t from 'ts-codec';
4
+ import { toQualifiedTableName } from '../utils/mssql.js';
5
+ import type { MSSQLTableReconciliationContext } from './MSSQLTableReconciliationContext.js';
6
+ import { MSSQLTableReconciliationState } from './MSSQLTableReconciliationContext.js';
7
+
8
+ /**
9
+ * The pinned capture instance was dropped and cannot be replaced in this stream.
10
+ */
11
+ export class CaptureInstanceMissingError extends ServiceError {
12
+ constructor(message: string) {
13
+ super(ErrorCode.PSYNC_S1601, message);
14
+ }
15
+ }
16
+
17
+ /**
18
+ * A configured table does not exist or does not have CDC enabled yet.
19
+ */
20
+ export class SourceTableNotReadyError extends ServiceError {
21
+ constructor(message: string) {
22
+ super(ErrorCode.PSYNC_S1602, message);
23
+ }
24
+ }
25
+
26
+ /**
27
+ * A replicated table is unavailable or no longer matches its persisted source binding.
28
+ */
29
+ export class SourceTableUnavailableError extends ServiceError {
30
+ constructor(message: string) {
31
+ super(ErrorCode.PSYNC_S1603, message);
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Persisted capture-table identity. Names are not enough because SQL Server can reuse them.
37
+ */
38
+ export const MSSQLSourceMetadata = t.object({
39
+ captureTableObjectId: t.number
40
+ });
41
+ export type MSSQLSourceMetadata = t.Decoded<typeof MSSQLSourceMetadata>;
42
+
43
+ /**
44
+ * Parse persisted capture metadata, returning null for legacy records.
45
+ */
46
+ export function readCaptureMetadata(value: JsonValue): MSSQLSourceMetadata | null {
47
+ if (value == null) {
48
+ return null;
49
+ }
50
+ return MSSQLSourceMetadata.decode(value as t.Encoded<typeof MSSQLSourceMetadata>);
51
+ }
52
+
53
+ /**
54
+ * Reconcile a discovered source-table state against persisted bindings. Ready tables reconcile
55
+ * against capture instances ordered newest first. New and legacy bindings use the newest instance;
56
+ * pinned bindings keep their instance or fail if it is gone.
57
+ */
58
+ export function createCaptureReconciler(context: MSSQLTableReconciliationContext) {
59
+ return (({ source, candidates }) => {
60
+ if (context.state === MSSQLTableReconciliationState.TABLE_MISSING) {
61
+ if (candidates.length > 0) {
62
+ // The table is missing, but we already recorded it. Display the corresponding error.
63
+ throw sourceTableUnavailableError(source);
64
+ }
65
+ throw new SourceTableNotReadyError(
66
+ `Source table ${toQualifiedTableName(source.schema, source.name)} from the sync configuration does not ` +
67
+ `exist. Create the table and enable CDC for it.`
68
+ );
69
+ }
70
+
71
+ // Apply capture pinning after the shared identity check.
72
+ const compatible: SourceTableCandidate[] = [];
73
+ const incompatibleTables: SourceTableCandidate[] = [];
74
+ for (const candidate of candidates) {
75
+ if (storage.sourceIdentityCompatible(source, candidate)) {
76
+ compatible.push(candidate);
77
+ } else {
78
+ incompatibleTables.push(candidate);
79
+ }
80
+ }
81
+
82
+ if (compatible.length === 0) {
83
+ if (candidates.length > 0) {
84
+ // An overlapping persisted binding with a different source identity is not a new table.
85
+ // This can happen when a table is dropped and recreated while replication is stopped.
86
+ // Reusing the old snapshot or replacing it during a normal job restart would silently
87
+ // adopt a different physical table without a sync config deployment boundary.
88
+ throw sourceTableUnavailableError(source);
89
+ }
90
+
91
+ if (context.state === MSSQLTableReconciliationState.CDC_DISABLED) {
92
+ throw new SourceTableNotReadyError(
93
+ `CDC is not enabled for source table ${toQualifiedTableName(source.schema, source.name)}, which ` +
94
+ `matches the sync configuration. Enable CDC for this table to start replicating it.`
95
+ );
96
+ }
97
+
98
+ // Pin a new binding to the newest instance.
99
+ const newest = context.captureInstances[0];
100
+ return {
101
+ compatibleTables: [],
102
+ incompatibleTables,
103
+ newTableValues: { sourceMetadata: captureMetadata(newest.objectId) }
104
+ };
105
+ }
106
+
107
+ // At least one compatible candidate anchors this process to the discovered source identity.
108
+ // Any remaining incompatible candidates are stale overlapping records, so storage may remove
109
+ // them without adopting a replacement table or changing the binding this process uses.
110
+ if (context.state === MSSQLTableReconciliationState.CDC_DISABLED) {
111
+ throw new CaptureInstanceMissingError(
112
+ `CDC is no longer enabled for source table ${toQualifiedTableName(source.schema, source.name)}. ` +
113
+ `Re-enable CDC, then redeploy the sync config to adopt the replacement capture instance. Its ` +
114
+ `already-replicated data is retained until the redeployed sync config becomes active.`
115
+ );
116
+ }
117
+
118
+ const availableInstances = context.captureInstances;
119
+
120
+ const pinnedObjectIds = new Set<number>();
121
+ let metadataFreeCount = 0;
122
+ for (const candidate of compatible) {
123
+ const metadata = readCaptureMetadata(candidate.sourceMetadata);
124
+ if (metadata == null) {
125
+ metadataFreeCount += 1;
126
+ } else {
127
+ pinnedObjectIds.add(metadata.captureTableObjectId);
128
+ }
129
+ }
130
+
131
+ // Never guess which capture schema existing snapshots belong to.
132
+ if (pinnedObjectIds.size > 0 && metadataFreeCount > 0) {
133
+ throw new ReplicationAssertionError(
134
+ `Source table ${toQualifiedTableName(source.schema, source.name)} has a mixture of legacy (metadata-free) and ` +
135
+ `capture-instance-pinned records. This is invalid persisted state.`
136
+ );
137
+ }
138
+ // All records for a physical table must use the same capture instance.
139
+ if (pinnedObjectIds.size > 1) {
140
+ throw new ReplicationAssertionError(
141
+ `Source table ${toQualifiedTableName(source.schema, source.name)} has multiple persisted capture identities ` +
142
+ `(${[...pinnedObjectIds].join(', ')}). This is invalid persisted state.`
143
+ );
144
+ }
145
+
146
+ if (pinnedObjectIds.size === 0) {
147
+ // Backfill legacy records with the instance the old code would have selected.
148
+ const newest = availableInstances[0];
149
+ const sourceMetadata = captureMetadata(newest.objectId);
150
+ return {
151
+ compatibleTables: compatible.map((candidate) => candidate.withSourceMetadata(sourceMetadata)),
152
+ incompatibleTables,
153
+ newTableValues: { sourceMetadata }
154
+ };
155
+ }
156
+
157
+ const [captureTableObjectId] = [...pinnedObjectIds];
158
+ const available = availableInstances.some((instance) => instance.objectId === captureTableObjectId);
159
+ if (!available) {
160
+ // A replacement may capture a different schema, so do not adopt it in place.
161
+ throw new CaptureInstanceMissingError(
162
+ `The CDC capture instance (object id ${captureTableObjectId}) for source table ` +
163
+ `${toQualifiedTableName(source.schema, source.name)} is no longer available. Deploy a new sync config to ` +
164
+ `replicate this table against a new capture instance.`
165
+ );
166
+ }
167
+ return {
168
+ compatibleTables: compatible,
169
+ incompatibleTables,
170
+ newTableValues: { sourceMetadata: captureMetadata(captureTableObjectId) }
171
+ };
172
+ }) satisfies storage.SourceTableCandidateReconciler;
173
+ }
174
+
175
+ function captureMetadata(captureTableObjectId: number): MSSQLSourceMetadata {
176
+ return { captureTableObjectId };
177
+ }
178
+
179
+ function sourceTableUnavailableError(source: { schema: string; name: string }): SourceTableUnavailableError {
180
+ return new SourceTableUnavailableError(
181
+ `Table ${toQualifiedTableName(source.schema, source.name)} no longer matches the source table binding ` +
182
+ `selected by this replication process. It may have been dropped and recreated, renamed, or had its ` +
183
+ `replication identity changed. Redeploy the sync config to adopt the replacement. Its already-replicated ` +
184
+ `data is retained until the redeployed sync config becomes active.`
185
+ );
186
+ }
@@ -11,6 +11,28 @@ export interface MSSQLConnectionManagerListener {
11
11
  onEnded(): void;
12
12
  }
13
13
 
14
+ export function createConnectionPoolConfig(
15
+ options: NormalizedMSSQLConnectionConfig,
16
+ poolOptions: sql.PoolOpts<sql.Connection>
17
+ ): sql.config {
18
+ return {
19
+ authentication: options.authentication,
20
+ user: options.username,
21
+ password: options.password,
22
+ server: options.hostname,
23
+ port: options.port,
24
+ database: options.database,
25
+ pool: poolOptions,
26
+ options: {
27
+ appName: `powersync/${POWERSYNC_VERSION}`,
28
+ encrypt: true, // Required for Azure
29
+ trustServerCertificate: options.additionalConfig.trustServerCertificate,
30
+ ...(options.tls_servername ? { serverName: options.tls_servername } : {}),
31
+ ...(options.cacert ? { cryptoCredentialsDetails: { ca: options.cacert } } : {})
32
+ }
33
+ };
34
+ }
35
+
14
36
  export class MSSQLConnectionManager extends BaseObserver<MSSQLConnectionManagerListener> {
15
37
  private readonly pool: sql.ConnectionPool;
16
38
 
@@ -20,20 +42,7 @@ export class MSSQLConnectionManager extends BaseObserver<MSSQLConnectionManagerL
20
42
  ) {
21
43
  super();
22
44
  // The pool is lazy - no connections are opened until a query is performed.
23
- this.pool = new sql.ConnectionPool({
24
- authentication: options.authentication,
25
- user: options.username,
26
- password: options.password,
27
- server: options.hostname,
28
- port: options.port,
29
- database: options.database,
30
- pool: poolOptions,
31
- options: {
32
- appName: `powersync/${POWERSYNC_VERSION}`,
33
- encrypt: true, // Required for Azure
34
- trustServerCertificate: options.additionalConfig.trustServerCertificate
35
- }
36
- });
45
+ this.pool = new sql.ConnectionPool(createConnectionPoolConfig(options, poolOptions));
37
46
  }
38
47
 
39
48
  public get connectionTag() {
@@ -0,0 +1,29 @@
1
+ import type { SourceEntityDescriptor } from '@powersync/service-core';
2
+ import type { CaptureInstance } from '../common/CaptureInstance.js';
3
+
4
+ export enum MSSQLTableReconciliationState {
5
+ TABLE_MISSING = 'table_missing',
6
+ CDC_DISABLED = 'cdc_disabled',
7
+ READY = 'ready'
8
+ }
9
+
10
+ interface BaseMSSQLTableReconciliationContext {
11
+ source: SourceEntityDescriptor;
12
+ }
13
+
14
+ export type MSSQLUnavailableTableReconciliationContext =
15
+ | (BaseMSSQLTableReconciliationContext & {
16
+ state: MSSQLTableReconciliationState.TABLE_MISSING;
17
+ })
18
+ | (BaseMSSQLTableReconciliationContext & {
19
+ state: MSSQLTableReconciliationState.CDC_DISABLED;
20
+ });
21
+
22
+ export type MSSQLReadyTableReconciliationContext = BaseMSSQLTableReconciliationContext & {
23
+ state: MSSQLTableReconciliationState.READY;
24
+ captureInstances: readonly CaptureInstance[];
25
+ };
26
+
27
+ export type MSSQLTableReconciliationContext =
28
+ | MSSQLUnavailableTableReconciliationContext
29
+ | MSSQLReadyTableReconciliationContext;
@@ -0,0 +1,79 @@
1
+ import { CaptureInstance } from '../common/CaptureInstance.js';
2
+ import { MSSQLSourceTable } from '../common/MSSQLSourceTable.js';
3
+ import { SourceTableChangeRef } from '../utils/schema.js';
4
+
5
+ /**
6
+ * Schema changes are detected to warn or error on, not applied automatically. Polling cannot be
7
+ * made atomic with a commit, so the replicated schema stays fixed until the next deploy.
8
+ *
9
+ * Drops and renames fail the job because they have no known LSN. Continuing could skip unread
10
+ * changes. Existing replicated data is kept for the next deploy to clean up.
11
+ */
12
+ export enum SchemaChangeType {
13
+ /**
14
+ * A replicated table was renamed.
15
+ */
16
+ TABLE_RENAME = 'table_rename',
17
+ /**
18
+ * A replicated table was dropped.
19
+ */
20
+ TABLE_DROP = 'table_drop',
21
+ /**
22
+ * The source columns changed. The pinned capture schema remains active.
23
+ */
24
+ TABLE_COLUMN_CHANGES = 'table_column_changes',
25
+ /**
26
+ * A newer capture instance exists, but the pinned one is still available.
27
+ */
28
+ NEW_CAPTURE_INSTANCE = 'new_capture_instance',
29
+ /**
30
+ * The pinned capture instance is no longer available.
31
+ */
32
+ MISSING_CAPTURE_INSTANCE = 'missing_capture_instance'
33
+ }
34
+
35
+ interface SchemaChangeBase<Type extends SchemaChangeType> {
36
+ type: Type;
37
+ /**
38
+ * The replicated table the change applies to.
39
+ */
40
+ table: MSSQLSourceTable;
41
+ }
42
+
43
+ export interface TableRenameChange extends SchemaChangeBase<SchemaChangeType.TABLE_RENAME> {
44
+ /**
45
+ * The name the table was renamed to. Only used in the error reported for the rename.
46
+ */
47
+ newTable: SourceTableChangeRef;
48
+ }
49
+
50
+ export type TableDropChange = SchemaChangeBase<SchemaChangeType.TABLE_DROP>;
51
+
52
+ export interface TableColumnChanges extends SchemaChangeBase<SchemaChangeType.TABLE_COLUMN_CHANGES> {
53
+ /**
54
+ * The pinned capture instance the drift was observed against.
55
+ */
56
+ captureInstance: CaptureInstance;
57
+ }
58
+
59
+ export interface NewCaptureInstanceChange extends SchemaChangeBase<SchemaChangeType.NEW_CAPTURE_INSTANCE> {
60
+ /**
61
+ * The newer instance that is available but will not be adopted by this stream.
62
+ */
63
+ newCaptureInstance: CaptureInstance;
64
+ }
65
+
66
+ export interface MissingCaptureInstanceChange extends SchemaChangeBase<SchemaChangeType.MISSING_CAPTURE_INSTANCE> {
67
+ /**
68
+ * A newer instance that replaced the pinned one, if CDC is still enabled for the table. Only used
69
+ * to report the right recovery step.
70
+ */
71
+ replacementInstance?: CaptureInstance;
72
+ }
73
+
74
+ export type SchemaChange =
75
+ | TableRenameChange
76
+ | TableDropChange
77
+ | TableColumnChanges
78
+ | NewCaptureInstanceChange
79
+ | MissingCaptureInstanceChange;
@@ -8,6 +8,10 @@ export const DEFAULT_POLLING_BATCH_SIZE = 10;
8
8
  export const DEFAULT_POLLING_INTERVAL_MS = 1000;
9
9
  export const MSSQL_CONNECTION_TYPE = 'mssql' as const;
10
10
 
11
+ const DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 60;
12
+ const MIN_HEARTBEAT_INTERVAL_SECONDS = 5;
13
+ const MAX_HEARTBEAT_INTERVAL_SECONDS = 60;
14
+
11
15
  export const AzureActiveDirectoryServicePrincipalSecret = t.object({
12
16
  type: t.literal('azure-active-directory-service-principal-secret'),
13
17
  options: t.object({
@@ -89,11 +93,19 @@ export interface NormalizedMSSQLConnectionConfig {
89
93
  database: string;
90
94
  schema?: string;
91
95
 
96
+ /** PEM-encoded certificate authority used to validate the SQL Server certificate. */
97
+ cacert?: string;
98
+
99
+ /** Server name to use when validating the SQL Server certificate. */
100
+ tls_servername?: string;
101
+
92
102
  authentication?: Authentication;
93
103
 
94
104
  lookup?: LookupFunction;
95
105
 
96
106
  additionalConfig: AdditionalConfig;
107
+
108
+ heartbeat_interval_seconds: number;
97
109
  }
98
110
 
99
111
  export const MSSQLConnectionConfig = service_types.configFile.DataSourceConfig.and(
@@ -107,10 +119,20 @@ export const MSSQLConnectionConfig = service_types.configFile.DataSourceConfig.a
107
119
  hostname: t.string.optional(),
108
120
  port: service_types.configFile.portCodec.optional(),
109
121
 
122
+ /** PEM-encoded certificate authority used to validate the SQL Server certificate. */
123
+ cacert: t.string.optional(),
124
+
125
+ /** Server name to use when validating the SQL Server certificate. */
126
+ tls_servername: t.string.optional(),
127
+
110
128
  authentication: Authentication.optional(),
111
129
 
112
130
  reject_ip_ranges: t.array(t.string).optional(),
113
- additionalConfig: AdditionalConfig.optional()
131
+ additionalConfig: AdditionalConfig.optional(),
132
+ /**
133
+ * Interval in seconds between source connection heartbeats. Null or omitted uses the default.
134
+ */
135
+ heartbeat_interval_seconds: service_types.orNull(t.number).optional()
114
136
  })
115
137
  );
116
138
 
@@ -169,6 +191,13 @@ export function normalizeConnectionConfig(options: MSSQLConnectionConfig): Norma
169
191
  throw new ServiceError(ErrorCode.PSYNC_S1105, `MSSQL connection: database required`);
170
192
  }
171
193
 
194
+ if (options.cacert && options.additionalConfig?.trustServerCertificate) {
195
+ throw new ServiceError(
196
+ ErrorCode.PSYNC_S1604,
197
+ 'MSSQL connection: cacert cannot be used with trustServerCertificate because certificate validation would be disabled'
198
+ );
199
+ }
200
+
172
201
  const lookup = makeHostnameLookupFunction(hostname, { reject_ip_ranges: options.reject_ip_ranges ?? [] });
173
202
 
174
203
  return {
@@ -180,6 +209,8 @@ export function normalizeConnectionConfig(options: MSSQLConnectionConfig): Norma
180
209
  hostname,
181
210
  port,
182
211
  database,
212
+ cacert: options.cacert,
213
+ tls_servername: options.tls_servername,
183
214
 
184
215
  lookup,
185
216
  authentication: options.authentication,
@@ -188,10 +219,24 @@ export function normalizeConnectionConfig(options: MSSQLConnectionConfig): Norma
188
219
  pollingIntervalMs: options.additionalConfig?.pollingIntervalMs ?? DEFAULT_POLLING_INTERVAL_MS,
189
220
  pollingBatchSize: options.additionalConfig?.pollingBatchSize ?? DEFAULT_POLLING_BATCH_SIZE,
190
221
  trustServerCertificate: options.additionalConfig?.trustServerCertificate ?? false
191
- }
222
+ },
223
+ heartbeat_interval_seconds: normalizeHeartbeatInterval(options.heartbeat_interval_seconds)
192
224
  } satisfies NormalizedMSSQLConnectionConfig;
193
225
  }
194
226
 
227
+ function normalizeHeartbeatInterval(value: number | null | undefined): number {
228
+ if (value == null) {
229
+ return DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
230
+ }
231
+ if (!Number.isFinite(value) || value < MIN_HEARTBEAT_INTERVAL_SECONDS || value > MAX_HEARTBEAT_INTERVAL_SECONDS) {
232
+ throw new ServiceError(
233
+ ErrorCode.PSYNC_S1109,
234
+ `MSSQL connection: heartbeat_interval_seconds must be between ${MIN_HEARTBEAT_INTERVAL_SECONDS} and ${MAX_HEARTBEAT_INTERVAL_SECONDS} seconds`
235
+ );
236
+ }
237
+ return value;
238
+ }
239
+
195
240
  export function baseUri(config: ResolvedMSSQLConnectionConfig) {
196
241
  return `mssql://${config.hostname}:${config.port}/${config.database}`;
197
242
  }
@@ -351,7 +351,7 @@ export async function getDebugTableInfo(options: GetDebugTableInfoOptions): Prom
351
351
  if (captureInstanceDetails && captureInstanceDetails.instances[0].pendingSchemaChanges.length > 0) {
352
352
  schemaDriftError = {
353
353
  level: 'warning',
354
- message: `Source table ${toQualifiedTableName(schema, table.name)} has schema changes not reflected in the CDC capture instance. Please disable and re-enable CDC on the source table to update the capture instance schema.
354
+ message: `Source table ${toQualifiedTableName(schema, table.name)} has schema changes not reflected in the CDC capture instance. Create a replacement CDC capture instance with the intended columns, update the sync config if needed, and deploy a new sync config. If the change requires disabling CDC, re-enable CDC before deploying.
355
355
  Pending schema changes: ${captureInstanceDetails.instances[0].pendingSchemaChanges.join(', \n')}`
356
356
  };
357
357
  }
@@ -1,4 +1,4 @@
1
- import { logger } from '@powersync/lib-services-framework';
1
+ import { ErrorCode, logger, ServiceError } from '@powersync/lib-services-framework';
2
2
  import { TablePattern } from '@powersync/service-sync-rules';
3
3
  import sql from 'mssql';
4
4
  import { MSSQLConnectionManager } from '../replication/MSSQLConnectionManager.js';
@@ -139,70 +139,76 @@ export async function getReplicationIdentityColumns(
139
139
  }
140
140
 
141
141
  export interface SourceTableChangeRef {
142
- objectId: number | string | undefined;
142
+ /**
143
+ * `sys.tables.object_id`, which SQL Server always reports as an int. Narrower than
144
+ * `SourceEntityDescriptor.objectId`, which has to accommodate other source databases.
145
+ */
146
+ objectId: number;
143
147
  schema: string;
144
148
  name: string;
145
149
  }
146
150
 
147
151
  export type ResolvedTable = SourceTableChangeRef;
148
152
 
153
+ export const SCHEMA_WILDCARD_MESSAGE =
154
+ 'Schema wildcards ("%") in table patterns are not supported for SQL Server connections.';
155
+
156
+ /**
157
+ * Wildcards would allow the replicated table set to change between polls, so they are rejected.
158
+ */
159
+ export function tableWildcardMessage(tablePattern: TablePattern): string {
160
+ return (
161
+ `Table wildcards ("%") are not supported for SQL Server connections: "${tablePattern.tablePattern}". ` +
162
+ `List each table explicitly.`
163
+ );
164
+ }
165
+
166
+ /**
167
+ * Returns the reason this pattern cannot be replicated, or null if it is supported.
168
+ */
169
+ export function unsupportedTablePatternMessage(tablePattern: TablePattern): string | null {
170
+ if (tablePattern.isSchemaWildcard) {
171
+ return SCHEMA_WILDCARD_MESSAGE;
172
+ }
173
+ if (tablePattern.isWildcard) {
174
+ return tableWildcardMessage(tablePattern);
175
+ }
176
+ return null;
177
+ }
178
+
149
179
  export async function getTablesFromPattern(
150
180
  connectionManager: MSSQLConnectionManager,
151
181
  tablePattern: TablePattern
152
182
  ): Promise<ResolvedTable[]> {
153
- if (tablePattern.isWildcard) {
154
- const { recordset: tableResults } = await connectionManager.query(
155
- `
156
- SELECT
157
- tbl.name AS [table],
158
- sch.name AS [schema],
159
- tbl.object_id AS object_id
160
- FROM sys.tables tbl
161
- JOIN sys.schemas sch ON tbl.schema_id = sch.schema_id
162
- WHERE sch.name = @schema
163
- AND tbl.name LIKE @tablePattern
164
- `,
165
- [
166
- { name: 'schema', type: sql.VarChar(sql.MAX), value: tablePattern.schema },
167
- { name: 'tablePattern', type: sql.VarChar(sql.MAX), value: tablePattern.tablePattern }
168
- ]
169
- );
170
-
171
- return tableResults
172
- .map((row) => {
173
- return {
174
- objectId: row.object_id,
175
- schema: row.schema,
176
- name: row.table
177
- };
178
- })
179
- .filter((table: ResolvedTable) => table.name.startsWith(tablePattern.tablePrefix));
180
- } else {
181
- const { recordset: tableResults } = await connectionManager.query(
182
- `
183
- SELECT
184
- tbl.name AS [table],
185
- sch.name AS [schema],
186
- tbl.object_id AS object_id
187
- FROM sys.tables tbl
188
- JOIN sys.schemas sch ON tbl.schema_id = sch.schema_id
189
- WHERE sch.name = @schema
190
- AND tbl.name = @tablePattern
191
- `,
192
- [
193
- { name: 'schema', type: sql.VarChar(sql.MAX), value: tablePattern.schema },
194
- { name: 'tablePattern', type: sql.VarChar(sql.MAX), value: tablePattern.tablePattern }
195
- ]
196
- );
197
-
198
- return tableResults.map((row) => {
199
- return {
200
- objectId: row.object_id,
201
- schema: row.schema,
202
- name: row.table
203
- };
204
- });
183
+ const unsupported = unsupportedTablePatternMessage(tablePattern);
184
+ if (unsupported != null) {
185
+ throw new ServiceError(ErrorCode.PSYNC_R2201, unsupported);
205
186
  }
187
+
188
+ const { recordset: tableResults } = await connectionManager.query(
189
+ `
190
+ SELECT
191
+ tbl.name AS [table],
192
+ sch.name AS [schema],
193
+ tbl.object_id AS object_id
194
+ FROM sys.tables tbl
195
+ JOIN sys.schemas sch ON tbl.schema_id = sch.schema_id
196
+ WHERE sch.name = @schema
197
+ AND tbl.name = @tablePattern
198
+ `,
199
+ [
200
+ { name: 'schema', type: sql.VarChar(sql.MAX), value: tablePattern.schema },
201
+ { name: 'tablePattern', type: sql.VarChar(sql.MAX), value: tablePattern.tablePattern }
202
+ ]
203
+ );
204
+
205
+ return tableResults.map((row) => {
206
+ return {
207
+ objectId: row.object_id,
208
+ schema: row.schema,
209
+ name: row.table
210
+ };
211
+ });
206
212
  }
207
213
 
208
214
  export interface GetPendingSchemaChangesOptions {