@nextlyhq/adapter-drizzle 0.0.2-alpha.50 → 0.0.2-alpha.52

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.
package/dist/index.mjs CHANGED
@@ -106,6 +106,36 @@ function createDatabaseError(options) {
106
106
  }
107
107
 
108
108
  // src/adapter.ts
109
+ var DATE_DATA_TYPE = /(?:^|\s)date$/;
110
+ var WALL_CLOCK_ALIAS_STEM = "__nx_wc";
111
+ var WALL_CLOCK_PATTERN = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?$/;
112
+ function parseWallClockAsUtc(text) {
113
+ const match = WALL_CLOCK_PATTERN.exec(text.trim());
114
+ if (!match) return void 0;
115
+ const [, year, month, day, hour, minute, second, fraction = ""] = match;
116
+ const millis = Number(`${fraction}000`.slice(0, 3));
117
+ const parsed = new Date(
118
+ Date.UTC(
119
+ Number(year),
120
+ Number(month) - 1,
121
+ Number(day),
122
+ Number(hour),
123
+ Number(minute),
124
+ Number(second),
125
+ millis
126
+ )
127
+ );
128
+ if (Number(year) < 100) parsed.setUTCFullYear(Number(year));
129
+ return parsed;
130
+ }
131
+ function isDateColumn(colDef) {
132
+ if (!colDef || typeof colDef !== "object") return false;
133
+ const candidate = colDef;
134
+ return typeof candidate.mapFromDriverValue === "function" && typeof candidate.mapToDriverValue === "function" && DATE_DATA_TYPE.test(String(candidate.dataType));
135
+ }
136
+ function carriesTimeZone(colDef) {
137
+ return colDef.withTimezone === true;
138
+ }
109
139
  function affectedRowCount(result) {
110
140
  if (Array.isArray(result)) {
111
141
  const header = result[0];
@@ -302,6 +332,180 @@ var DrizzleAdapter = class {
302
332
  }
303
333
  return out;
304
334
  }
335
+ /**
336
+ * Decode a raw-SQL result row's DATE column values the way a Drizzle query
337
+ * would, so a write answers with the same representation a read of the same
338
+ * column gives.
339
+ *
340
+ * A Drizzle query path runs every value through its column definition; a
341
+ * raw-SQL path does not, so a dialect that stores a timestamp as a number
342
+ * answers a write with that number while every read answers a `Date`. Only
343
+ * date columns are touched, and a value that is already a `Date` is left
344
+ * alone, so a driver that decodes on its own is unaffected.
345
+ *
346
+ * Runs after {@link mapRowKeysToJs}: keys are Drizzle property names by then,
347
+ * which is what the table definition is keyed by.
348
+ */
349
+ mapDateValuesFromDriver(tableObj, row) {
350
+ if (!tableObj || typeof tableObj !== "object" || !row || typeof row !== "object") {
351
+ return row;
352
+ }
353
+ let decoded;
354
+ for (const [jsName, colDef] of Object.entries(
355
+ tableObj
356
+ )) {
357
+ if (!isDateColumn(colDef)) continue;
358
+ const value = row[jsName];
359
+ if (value == null || value instanceof Date) continue;
360
+ decoded ??= { ...row };
361
+ decoded[jsName] = colDef.mapFromDriverValue(value);
362
+ }
363
+ return decoded ?? row;
364
+ }
365
+ /**
366
+ * Encode a row's DATE values the way a Drizzle query would before binding
367
+ * them, so what lands in the column does not depend on the server's timezone.
368
+ *
369
+ * A column declared without a time zone stores a wall clock and records
370
+ * nothing about which zone it belongs to, so both ends have to agree. Drizzle
371
+ * writes UTC and reads UTC. A driver handed a `Date` writes the LOCAL wall
372
+ * clock instead, and the same row then reads back shifted by the offset --
373
+ * on a UTC server the two agree and nothing is visibly wrong, which is why
374
+ * this survives CI.
375
+ *
376
+ * Only date columns are touched. A value that is not a `Date` is left as it
377
+ * is, so a caller that already encoded one is not encoded twice.
378
+ *
379
+ * Keys may be spelled either way at this point, so both the Drizzle property
380
+ * name and the SQL column name resolve.
381
+ */
382
+ mapDateValuesToDriver(tableObj, data) {
383
+ if (!tableObj || typeof tableObj !== "object" || !data) return data;
384
+ const dateColumns = /* @__PURE__ */ new Map();
385
+ for (const [jsName, colDef] of Object.entries(
386
+ tableObj
387
+ )) {
388
+ if (!isDateColumn(colDef)) continue;
389
+ dateColumns.set(jsName, colDef);
390
+ const sqlName = colDef.name;
391
+ if (typeof sqlName === "string") dateColumns.set(sqlName, colDef);
392
+ }
393
+ if (dateColumns.size === 0) return data;
394
+ let encoded;
395
+ for (const [key, value] of Object.entries(data)) {
396
+ if (!(value instanceof Date)) continue;
397
+ const column = dateColumns.get(key);
398
+ if (!column) continue;
399
+ encoded ??= { ...data };
400
+ encoded[key] = column.mapToDriverValue(value);
401
+ }
402
+ return encoded ?? data;
403
+ }
404
+ /**
405
+ * Bring a row about to be written through a raw-SQL statement into the shape
406
+ * a Drizzle query would have bound: SQL column names for keys, encoded values
407
+ * for date columns.
408
+ *
409
+ * The mirror of {@link mapRowFromRawSql}. The raw-SQL write paths exist
410
+ * because a dialect needs SQL a Drizzle query cannot express, not because
411
+ * their callers want different values in the table.
412
+ */
413
+ mapRowToRawSql(tableObj, data) {
414
+ return this.mapDateValuesToDriver(
415
+ tableObj,
416
+ this.mapKeysToSqlColumns(tableObj, data)
417
+ );
418
+ }
419
+ /**
420
+ * Bring a raw-SQL result row into the shape a Drizzle query would have
421
+ * produced: Drizzle property names for keys, decoded values for date columns.
422
+ *
423
+ * The raw-SQL write paths exist because a dialect needs SQL a Drizzle query
424
+ * cannot express, not because their callers want a different row shape, so
425
+ * every one of them ends here.
426
+ */
427
+ mapRowFromRawSql(tableObj, row, aliases = []) {
428
+ const mapped = this.mapDateValuesFromDriver(
429
+ tableObj,
430
+ this.mapRowKeysToJs(tableObj, row)
431
+ );
432
+ return this.applyWallClockAliases(mapped, aliases);
433
+ }
434
+ /**
435
+ * The date columns a statement is about to return, and the alias each one's
436
+ * wall clock is spelled out under.
437
+ *
438
+ * A driver turns a timestamp into a `Date` using ITS zone before any of this
439
+ * code runs, and that conversion is lossy: a wall clock inside a
440
+ * daylight-saving gap is a local time that does not exist, so the driver
441
+ * normalizes it and the original is gone. Asking the database for the wall
442
+ * clock as text alongside the row is the only way to read it exactly.
443
+ *
444
+ * `"*"` covers every date column; a projection covers only the ones it asked
445
+ * for, so a caller still gets back what it requested and nothing more.
446
+ */
447
+ dateWallClockAliases(tableObj, returning) {
448
+ if (!tableObj || typeof tableObj !== "object" || returning === void 0) {
449
+ return [];
450
+ }
451
+ const requested = returning === "*" ? void 0 : new Set(returning.map(String));
452
+ const taken = /* @__PURE__ */ new Set();
453
+ for (const [jsName, colDef] of Object.entries(
454
+ tableObj
455
+ )) {
456
+ taken.add(jsName);
457
+ const columnName = colDef.name;
458
+ if (typeof columnName === "string") taken.add(columnName);
459
+ }
460
+ let next = 0;
461
+ const freeAlias = () => {
462
+ let candidate = `${WALL_CLOCK_ALIAS_STEM}${next++}`;
463
+ while (taken.has(candidate)) {
464
+ candidate = `${WALL_CLOCK_ALIAS_STEM}${next++}`;
465
+ }
466
+ taken.add(candidate);
467
+ return candidate;
468
+ };
469
+ const aliases = [];
470
+ for (const [jsName, colDef] of Object.entries(
471
+ tableObj
472
+ )) {
473
+ if (!isDateColumn(colDef)) continue;
474
+ if (carriesTimeZone(colDef)) continue;
475
+ const sqlName = colDef.name;
476
+ if (typeof sqlName !== "string") continue;
477
+ if (requested && !requested.has(sqlName) && !requested.has(jsName)) {
478
+ continue;
479
+ }
480
+ aliases.push({ sqlName, alias: freeAlias(), jsName });
481
+ }
482
+ return aliases;
483
+ }
484
+ /**
485
+ * Replace each date in a row with the wall clock the database spelled out,
486
+ * read as UTC, and drop the aliases that carried it.
487
+ *
488
+ * The statement writes a UTC wall clock, so reading one back as UTC is what
489
+ * makes a write and a later read agree. Whatever the column actually stored
490
+ * is what arrives -- a column keeping only whole seconds reports whole
491
+ * seconds -- because this is the database's own text, not a value
492
+ * reconstructed from the one that was bound.
493
+ */
494
+ applyWallClockAliases(row, aliases) {
495
+ if (!row || typeof row !== "object" || aliases.length === 0) return row;
496
+ const record = row;
497
+ let resolved;
498
+ for (const { alias, jsName } of aliases) {
499
+ if (!(alias in record)) continue;
500
+ resolved ??= { ...record };
501
+ const text = resolved[alias];
502
+ delete resolved[alias];
503
+ if (typeof text !== "string") continue;
504
+ const parsed = parseWallClockAsUtc(text);
505
+ if (parsed !== void 0) resolved[jsName] = parsed;
506
+ }
507
+ return resolved ?? row;
508
+ }
305
509
  /**
306
510
  * Build a Drizzle column projection object (`{ propertyName: column }`) from a
307
511
  * requested column list, used by `select` (columns) and `insert` (returning).
@@ -1070,11 +1274,15 @@ var DrizzleAdapter = class {
1070
1274
  sql = `
1071
1275
  SELECT EXISTS (
1072
1276
  SELECT FROM information_schema.tables
1073
- WHERE table_schema = $1
1277
+ WHERE table_schema = COALESCE($1, (
1278
+ SELECT n.nspname FROM pg_class c
1279
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1280
+ WHERE c.oid = to_regclass($2)
1281
+ ))
1074
1282
  AND table_name = $2
1075
1283
  ) as exists
1076
1284
  `;
1077
- params.push(schema ?? "public", tableName);
1285
+ params.push(schema ?? null, tableName);
1078
1286
  break;
1079
1287
  case "mysql":
1080
1288
  sql = `