alchemy 0.76.1 → 0.77.1

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 (123) hide show
  1. package/bin/alchemy.js +109 -29
  2. package/bin/services/execute-alchemy.ts +10 -1
  3. package/lib/aws/ec2/index.d.ts +1 -0
  4. package/lib/aws/ec2/index.d.ts.map +1 -1
  5. package/lib/aws/ec2/index.js +1 -0
  6. package/lib/aws/ec2/index.js.map +1 -1
  7. package/lib/aws/index.d.ts +1 -7
  8. package/lib/aws/index.d.ts.map +1 -1
  9. package/lib/aws/index.js +1 -8
  10. package/lib/aws/index.js.map +1 -1
  11. package/lib/cloudflare/bucket-custom-domain.d.ts +90 -0
  12. package/lib/cloudflare/bucket-custom-domain.d.ts.map +1 -0
  13. package/lib/cloudflare/bucket-custom-domain.js +81 -0
  14. package/lib/cloudflare/bucket-custom-domain.js.map +1 -0
  15. package/lib/cloudflare/bucket.d.ts +28 -4
  16. package/lib/cloudflare/bucket.d.ts.map +1 -1
  17. package/lib/cloudflare/bucket.js +41 -14
  18. package/lib/cloudflare/bucket.js.map +1 -1
  19. package/lib/cloudflare/cloudflare-env-proxy.d.ts.map +1 -1
  20. package/lib/cloudflare/cloudflare-env-proxy.js +0 -3
  21. package/lib/cloudflare/cloudflare-env-proxy.js.map +1 -1
  22. package/lib/cloudflare/compatibility-date.gen.d.ts +1 -1
  23. package/lib/cloudflare/compatibility-date.gen.js +1 -1
  24. package/lib/cloudflare/container.d.ts.map +1 -1
  25. package/lib/cloudflare/container.js +8 -5
  26. package/lib/cloudflare/container.js.map +1 -1
  27. package/lib/cloudflare/d1-database.d.ts +13 -3
  28. package/lib/cloudflare/d1-database.d.ts.map +1 -1
  29. package/lib/cloudflare/d1-database.js +31 -15
  30. package/lib/cloudflare/d1-database.js.map +1 -1
  31. package/lib/cloudflare/index.d.ts +1 -0
  32. package/lib/cloudflare/index.d.ts.map +1 -1
  33. package/lib/cloudflare/index.js +1 -0
  34. package/lib/cloudflare/index.js.map +1 -1
  35. package/lib/cloudflare/miniflare/remote-binding-proxy.d.ts.map +1 -1
  36. package/lib/cloudflare/miniflare/remote-binding-proxy.js +73 -9
  37. package/lib/cloudflare/miniflare/remote-binding-proxy.js.map +1 -1
  38. package/lib/cloudflare/react-router/plugin.d.ts +2 -1
  39. package/lib/cloudflare/react-router/plugin.d.ts.map +1 -1
  40. package/lib/cloudflare/react-router/plugin.js +6 -14
  41. package/lib/cloudflare/react-router/plugin.js.map +1 -1
  42. package/lib/cloudflare/vite/plugin.d.ts.map +1 -1
  43. package/lib/cloudflare/vite/plugin.js +0 -3
  44. package/lib/cloudflare/vite/plugin.js.map +1 -1
  45. package/lib/cloudflare/worker-bundle.d.ts.map +1 -1
  46. package/lib/cloudflare/worker-bundle.js +17 -0
  47. package/lib/cloudflare/worker-bundle.js.map +1 -1
  48. package/lib/cloudflare/worker-metadata.d.ts.map +1 -1
  49. package/lib/cloudflare/worker-metadata.js +6 -4
  50. package/lib/cloudflare/worker-metadata.js.map +1 -1
  51. package/lib/cloudflare/worker-subdomain.d.ts.map +1 -1
  52. package/lib/cloudflare/worker-subdomain.js +0 -1
  53. package/lib/cloudflare/worker-subdomain.js.map +1 -1
  54. package/lib/cloudflare/worker.d.ts.map +1 -1
  55. package/lib/cloudflare/worker.js +28 -38
  56. package/lib/cloudflare/worker.js.map +1 -1
  57. package/lib/cloudflare/wrangler.json.d.ts +2 -281
  58. package/lib/cloudflare/wrangler.json.d.ts.map +1 -1
  59. package/lib/cloudflare/wrangler.json.js +23 -11
  60. package/lib/cloudflare/wrangler.json.js.map +1 -1
  61. package/lib/docker/api.d.ts +4 -0
  62. package/lib/docker/api.d.ts.map +1 -1
  63. package/lib/docker/api.js +3 -0
  64. package/lib/docker/api.js.map +1 -1
  65. package/lib/docker/image.d.ts +50 -12
  66. package/lib/docker/image.d.ts.map +1 -1
  67. package/lib/docker/image.js +86 -58
  68. package/lib/docker/image.js.map +1 -1
  69. package/lib/docker/remote-image.d.ts +1 -0
  70. package/lib/docker/remote-image.d.ts.map +1 -1
  71. package/lib/docker/remote-image.js +2 -0
  72. package/lib/docker/remote-image.js.map +1 -1
  73. package/lib/encrypt.d.ts +28 -3
  74. package/lib/encrypt.d.ts.map +1 -1
  75. package/lib/encrypt.js +77 -3
  76. package/lib/encrypt.js.map +1 -1
  77. package/lib/planetscale/role.d.ts +9 -0
  78. package/lib/planetscale/role.d.ts.map +1 -1
  79. package/lib/planetscale/role.js +18 -3
  80. package/lib/planetscale/role.js.map +1 -1
  81. package/lib/prisma-postgres/api.d.ts.map +1 -1
  82. package/lib/prisma-postgres/api.js +1 -0
  83. package/lib/prisma-postgres/api.js.map +1 -1
  84. package/lib/scope.d.ts +5 -0
  85. package/lib/scope.d.ts.map +1 -1
  86. package/lib/scope.js +23 -0
  87. package/lib/scope.js.map +1 -1
  88. package/lib/serde.js +1 -1
  89. package/lib/serde.js.map +1 -1
  90. package/lib/util/telemetry.js +4 -0
  91. package/lib/util/telemetry.js.map +1 -1
  92. package/package.json +12 -10
  93. package/src/aws/ec2/index.ts +1 -0
  94. package/src/aws/index.ts +1 -9
  95. package/src/cloudflare/bucket-custom-domain.ts +281 -0
  96. package/src/cloudflare/bucket.ts +85 -18
  97. package/src/cloudflare/cloudflare-env-proxy.ts +0 -3
  98. package/src/cloudflare/compatibility-date.gen.ts +1 -1
  99. package/src/cloudflare/container.ts +10 -7
  100. package/src/cloudflare/d1-database.ts +44 -6
  101. package/src/cloudflare/index.ts +1 -0
  102. package/src/cloudflare/miniflare/remote-binding-proxy.ts +80 -9
  103. package/src/cloudflare/react-router/plugin.ts +9 -21
  104. package/src/cloudflare/vite/plugin.ts +0 -3
  105. package/src/cloudflare/worker-bundle.ts +28 -1
  106. package/src/cloudflare/worker-metadata.ts +8 -4
  107. package/src/cloudflare/worker-subdomain.ts +0 -1
  108. package/src/cloudflare/worker.ts +32 -45
  109. package/src/cloudflare/wrangler.json.ts +62 -397
  110. package/src/docker/api.ts +7 -0
  111. package/src/docker/image.ts +164 -89
  112. package/src/docker/remote-image.ts +3 -0
  113. package/src/encrypt.ts +115 -3
  114. package/src/planetscale/role.ts +30 -3
  115. package/src/prisma-postgres/api.ts +1 -0
  116. package/src/scope.ts +27 -0
  117. package/src/serde.ts +1 -1
  118. package/src/util/telemetry.ts +5 -0
  119. package/workers/cloudflare-state-store.js +4802 -8
  120. package/workers/dofs-state-store.js +632 -2
  121. package/workers/remote-binding-proxy.js +1929 -3
  122. package/workers/tunnel-proxy.js +58 -6
  123. package/workers/tunnel-proxy.ts +1 -1
@@ -1,20 +1,4814 @@
1
- var Es=Object.defineProperty;var js=(r,e)=>{for(var t in e)Es(r,t,{get:e[t],enumerable:!0})};import{DurableObject as Xs}from"cloudflare:workers";var l=Symbol.for("drizzle:entityKind"),ri=Symbol.for("drizzle:hasOwnEntityKind");function m(r,e){if(!r||typeof r!="object")return!1;if(r instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,l))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=Object.getPrototypeOf(r).constructor;if(t)for(;t;){if(l in t&&t[l]===e[l])return!0;t=Object.getPrototypeOf(t)}return!1}var pt=class{static[l]="ConsoleLogWriter";write(e){console.log(e)}},_e=class{static[l]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new pt}logQuery(e,t){let s=t.map(n=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=s.length?` -- params: [${s.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}},De=class{static[l]="NoopLogger";logQuery(){}};var j=Symbol.for("drizzle:Name");var Re=Symbol.for("drizzle:Schema"),Ke=Symbol.for("drizzle:Columns"),Nr=Symbol.for("drizzle:ExtraConfigColumns"),yt=Symbol.for("drizzle:OriginalName"),gt=Symbol.for("drizzle:BaseName"),we=Symbol.for("drizzle:IsAlias"),Tr=Symbol.for("drizzle:ExtraConfigBuilder"),_s=Symbol.for("drizzle:IsDrizzleTable"),h=class{static[l]="Table";static Symbol={Name:j,Schema:Re,OriginalName:yt,Columns:Ke,ExtraConfigColumns:Nr,BaseName:gt,IsAlias:we,ExtraConfigBuilder:Tr};[j];[yt];[Re];[Ke];[Nr];[gt];[we]=!1;[_s]=!0;[Tr]=void 0;constructor(e,t,s){this[j]=this[yt]=e,this[Re]=t,this[gt]=s}};function se(r){return r[j]}function oe(r){return`${r[Re]??"public"}.${r[j]}`}var w=class{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[l]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}};var he=class{static[l]="ColumnBuilder";config;constructor(e,t,s){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:s,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===""&&(this.config.name=e)}};var Fe=class{static[l]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){this.reference=()=>{let{name:s,columns:i,foreignColumns:n}=e();return{name:s,columns:i,foreignTable:n[0].table,foreignColumns:n}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new bt(e,this)}},bt=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[l]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:s}=this.reference(),i=t.map(u=>u.name),n=s.map(u=>u.name),a=[this.table[j],...i,s[0].table[j],...n];return e??`${a.join("_")}_fk`}};function Ie(r,...e){return r(...e)}function xt(r,e){return`${r[j]}_${e.join("_")}_unique`}var St=class{constructor(e,t){this.name=t,this.columns=e}static[l]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new wt(e,this.columns,this.nullsNotDistinctConfig,this.name)}},$r=class{static[l]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new St(e,this.name)}},wt=class{constructor(e,t,s,i){this.table=e,this.columns=t,this.name=i??xt(this.table,this.columns.map(n=>n.name)),this.nullsNotDistinct=s}static[l]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}};function qr(r,e,t){for(let s=e;s<r.length;s++){let i=r[s];if(i==="\\"){s++;continue}if(i==='"')return[r.slice(e,s).replace(/\\/g,""),s+1];if(!t&&(i===","||i==="}"))return[r.slice(e,s).replace(/\\/g,""),s]}return[r.slice(e).replace(/\\/g,""),r.length]}function vr(r,e=0){let t=[],s=e,i=!1;for(;s<r.length;){let n=r[s];if(n===","){(i||s===e)&&t.push(""),i=!0,s++;continue}if(i=!1,n==="\\"){s+=2;continue}if(n==='"'){let[f,d]=qr(r,s+1,!0);t.push(f),s=d;continue}if(n==="}")return[t,s+1];if(n==="{"){let[f,d]=vr(r,s+1);t.push(f),s=d;continue}let[a,u]=qr(r,s,!1);t.push(a),s=u}return[t,s]}function Qr(r){let[e]=vr(r,1);return e}function Ct(r){return`{${r.map(e=>Array.isArray(e)?Ct(e):typeof e=="string"?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}var de=class extends he{foreignKeyConfigs=[];static[l]="PgColumnBuilder";array(e){return new Tt(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:s,actions:i})=>Ie((n,a)=>{let u=new Fe(()=>{let f=n();return{columns:[e],foreignColumns:[f]}});return a.onUpdate&&u.onUpdate(a.onUpdate),a.onDelete&&u.onDelete(a.onDelete),u.build(t)},s,i))}buildExtraConfigColumn(e){return new Nt(e,this.config)}},ae=class extends w{constructor(e,t){t.uniqueName||(t.uniqueName=xt(e,[t.name])),super(e,t),this.table=e}static[l]="PgColumn"},Nt=class extends ae{static[l]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}},Lr=class{static[l]="IndexedColumn";constructor(e,t,s,i){this.name=e,this.keyAsName=t,this.type=s,this.indexConfig=i}name;keyAsName;type;indexConfig},Tt=class extends de{static[l]="PgArrayBuilder";constructor(e,t,s){super(e,"array","PgArray"),this.config.baseBuilder=t,this.config.size=s}build(e){let t=this.config.baseBuilder.build(e);return new $t(e,this.config,t)}},$t=class r extends ae{constructor(e,t,s,i){super(e,t),this.baseColumn=s,this.range=i,this.size=t.size}size;static[l]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size=="number"?this.size:""}]`}mapFromDriverValue(e){return typeof e=="string"&&(e=Qr(e)),e.map(t=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let s=e.map(i=>i===null?null:m(this.baseColumn,r)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));return t?s:Ct(s)}};var Or=class extends de{static[l]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn"),this.config.enum=t}build(e){return new qt(e,this.config)}},qt=class extends ae{static[l]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}},Br=Symbol.for("drizzle:isPgEnum");function Pr(r){return!!r&&typeof r=="function"&&Br in r&&r[Br]===!0}var Ar=class extends de{static[l]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn"),this.config.enum=t}build(e){return new vt(e,this.config)}},vt=class extends ae{static[l]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};var O=class{static[l]="Subquery";constructor(e,t,s,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:s,isWith:i,usedTables:n}}},pe=class extends O{static[l]="WithSubquery"};var Er="0.44.6";var Qt,Lt,jr={startActiveSpan(r,e){return Qt?(Lt||(Lt=Qt.trace.getTracer("drizzle-orm",Er)),Ie((t,s)=>s.startActiveSpan(r,i=>{try{return e(i)}catch(n){throw i.setStatus({code:t.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{i.end()}}),Qt,Lt)):e()}};var T=Symbol.for("drizzle:ViewBaseConfig");var _r=class{static[l]="FakePrimitiveParam"};function Ot(r){return r!=null&&typeof r.getSQL=="function"}function Ds(r){let e={sql:"",params:[]};for(let t of r)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}var A=class{static[l]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new p([this])}},p=class r{constructor(e){this.queryChunks=e;for(let t of e)if(m(t,h)){let s=t[h.Symbol.Schema];this.usedTables.push(s===void 0?t[h.Symbol.Name]:s+"."+t[h.Symbol.Name])}}static[l]="SQL";decoder=Rr;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return jr.startActiveSpan("drizzle.buildSQL",t=>{let s=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":s.sql,"drizzle.query.params":JSON.stringify(s.params)}),s})}buildQueryFromSourceParams(e,t){let s=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:i,escapeName:n,escapeParam:a,prepareTyping:u,inlineParams:f,paramStartIndex:d}=s;return Ds(e.map(c=>{if(m(c,A))return{sql:c.value.join(""),params:[]};if(m(c,xe))return{sql:n(c.value),params:[]};if(c===void 0)return{sql:"",params:[]};if(Array.isArray(c)){let y=[new A("(")];for(let[b,N]of c.entries())y.push(N),b<c.length-1&&y.push(new A(", "));return y.push(new A(")")),this.buildQueryFromSourceParams(y,s)}if(m(c,r))return this.buildQueryFromSourceParams(c.queryChunks,{...s,inlineParams:f||c.shouldInlineParams});if(m(c,h)){let y=c[h.Symbol.Schema],b=c[h.Symbol.Name];return{sql:y===void 0||c[we]?n(b):n(y)+"."+n(b),params:[]}}if(m(c,w)){let y=i.getColumnCasing(c);if(t.invokeSource==="indexes")return{sql:n(y),params:[]};let b=c.table[h.Symbol.Schema];return{sql:c.table[we]||b===void 0?n(c.table[h.Symbol.Name])+"."+n(y):n(b)+"."+n(c.table[h.Symbol.Name])+"."+n(y),params:[]}}if(m(c,I)){let y=c[T].schema,b=c[T].name;return{sql:y===void 0||c[T].isAlias?n(b):n(y)+"."+n(b),params:[]}}if(m(c,R)){if(m(c.value,ee))return{sql:a(d.value++,c),params:[c],typings:["none"]};let y=c.value===null?null:c.encoder.mapToDriverValue(c.value);if(m(y,r))return this.buildQueryFromSourceParams([y],s);if(f)return{sql:this.mapInlineParam(y,s),params:[]};let b=["none"];return u&&(b=[u(c.encoder)]),{sql:a(d.value++,y),params:[y],typings:b}}return m(c,ee)?{sql:a(d.value++,c),params:[c],typings:["none"]}:m(c,r.Aliased)&&c.fieldAlias!==void 0?{sql:n(c.fieldAlias),params:[]}:m(c,O)?c._.isWith?{sql:n(c._.alias),params:[]}:this.buildQueryFromSourceParams([new A("("),c._.sql,new A(") "),new xe(c._.alias)],s):Pr(c)?c.schema?{sql:n(c.schema)+"."+n(c.enumName),params:[]}:{sql:n(c.enumName),params:[]}:Ot(c)?c.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([c.getSQL()],s):this.buildQueryFromSourceParams([new A("("),c.getSQL(),new A(")")],s):f?{sql:this.mapInlineParam(c,s),params:[]}:{sql:a(d.value++,c),params:[c],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){let s=e.toString();return t(s==="[object Object]"?JSON.stringify(e):s)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new r.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},xe=class{constructor(e){this.value=e}static[l]="Name";brand;getSQL(){return new p([this])}};function Dr(r){return typeof r=="object"&&r!==null&&"mapToDriverValue"in r&&typeof r.mapToDriverValue=="function"}var Rr={mapFromDriverValue:r=>r},Kr={mapToDriverValue:r=>r},ki={...Rr,...Kr},R=class{constructor(e,t=Kr){this.value=e,this.encoder=t}static[l]="Param";brand;getSQL(){return new p([this])}};function o(r,...e){let t=[];(e.length>0||r.length>0&&r[0]!=="")&&t.push(new A(r[0]));for(let[s,i]of e.entries())t.push(i,new A(r[s+1]));return new p(t)}(r=>{function e(){return new p([])}r.empty=e;function t(f){return new p(f)}r.fromList=t;function s(f){return new p([new A(f)])}r.raw=s;function i(f,d){let c=[];for(let[y,b]of f.entries())y>0&&d!==void 0&&c.push(d),c.push(b);return new p(c)}r.join=i;function n(f){return new xe(f)}r.identifier=n;function a(f){return new ee(f)}r.placeholder=a;function u(f,d){return new R(f,d)}r.param=u})(o||(o={}));(r=>{class e{constructor(s,i){this.sql=s,this.fieldAlias=i}static[l]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}r.Aliased=e})(p||(p={}));var ee=class{constructor(e){this.name=e}static[l]="Placeholder";getSQL(){return new p([this])}};function Ce(r,e){return r.map(t=>{if(m(t,ee)){if(!(t.name in e))throw new Error(`No value for placeholder "${t.name}" was provided`);return e[t.name]}if(m(t,R)&&m(t.value,ee)){if(!(t.value.name in e))throw new Error(`No value for placeholder "${t.value.name}" was provided`);return t.encoder.mapToDriverValue(e[t.value.name])}return t})}var Rs=Symbol.for("drizzle:IsDrizzleView"),I=class{static[l]="View";[T];[Rs]=!0;constructor({name:e,schema:t,selectedFields:s,query:i}){this[T]={name:e,originalName:e,schema:t,selectedFields:s,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new p([this])}};w.prototype.getSQL=function(){return new p([this])};h.prototype.getSQL=function(){return new p([this])};O.prototype.getSQL=function(){return new p([this])};function Bt(r,e,t){let s={},i=r.reduce((n,{path:a,field:u},f)=>{let d;m(u,w)?d=u:m(u,p)?d=u.decoder:d=u.sql.decoder;let c=n;for(let[y,b]of a.entries())if(y<a.length-1)b in c||(c[b]={}),c=c[b];else{let N=e[f],v=c[b]=N===null?null:d.mapFromDriverValue(N);if(t&&m(u,w)&&a.length===2){let S=a[0];S in s?typeof s[S]=="string"&&s[S]!==se(u.table)&&(s[S]=!1):s[S]=v===null?se(u.table):!1}}return n},{});if(t&&Object.keys(s).length>0)for(let[n,a]of Object.entries(s))typeof a=="string"&&!t[a]&&(i[n]=null);return i}function V(r,e){return Object.entries(r).reduce((t,[s,i])=>{if(typeof s!="string")return t;let n=e?[...e,s]:[s];return m(i,w)||m(i,p)||m(i,p.Aliased)?t.push({path:n,field:i}):m(i,h)?t.push(...V(i[h.Symbol.Columns],n)):t.push(...V(i,n)),t},[])}function Ne(r,e){let t=Object.keys(r),s=Object.keys(e);if(t.length!==s.length)return!1;for(let[i,n]of t.entries())if(n!==s[i])return!1;return!0}function Me(r,e){let t=Object.entries(e).filter(([,s])=>s!==void 0).map(([s,i])=>m(i,p)||m(i,w)?[s,i]:[s,new R(i,r[h.Symbol.Columns][s])]);if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function Fr(r,e){for(let t of e)for(let s of Object.getOwnPropertyNames(t.prototype))s!=="constructor"&&Object.defineProperty(r.prototype,s,Object.getOwnPropertyDescriptor(t.prototype,s)||Object.create(null))}function ze(r){return r[h.Symbol.Columns]}function Te(r){return m(r,O)?r._.alias:m(r,I)?r[T].name:m(r,p)?void 0:r[h.Symbol.IsAlias]?r[h.Symbol.Name]:r[h.Symbol.BaseName]}function Y(r,e){return{name:typeof r=="string"&&r.length>0?r:"",config:typeof r=="object"?r:e}}var At=typeof TextDecoder>"u"?null:new TextDecoder;var Ir=Symbol.for("drizzle:PgInlineForeignKeys"),Mr=Symbol.for("drizzle:EnableRLS"),Ve=class extends h{static[l]="PgTable";static Symbol=Object.assign({},h.Symbol,{InlineForeignKeys:Ir,EnableRLS:Mr});[Ir]=[];[Mr]=!1;[h.Symbol.ExtraConfigBuilder]=void 0;[h.Symbol.ExtraConfigColumns]={}};var Ue=class{static[l]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Pt(e,this.columns,this.name)}},Pt=class{constructor(e,t,s){this.table=e,this.columns=t,this.name=s}static[l]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Ve.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}};function K(r,e){return Dr(e)&&!Ot(r)&&!m(r,R)&&!m(r,ee)&&!m(r,w)&&!m(r,h)&&!m(r,I)?new R(r,e):r}var M=(r,e)=>o`${r} = ${K(e,r)}`,zr=(r,e)=>o`${r} <> ${K(e,r)}`;function te(...r){let e=r.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new p(e):new p([new A("("),o.join(e,new A(" and ")),new A(")")])}function Vr(...r){let e=r.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new p(e):new p([new A("("),o.join(e,new A(" or ")),new A(")")])}function Ur(r){return o`not ${r}`}var Jr=(r,e)=>o`${r} > ${K(e,r)}`,kr=(r,e)=>o`${r} >= ${K(e,r)}`,Wr=(r,e)=>o`${r} < ${K(e,r)}`,Hr=(r,e)=>o`${r} <= ${K(e,r)}`;function Je(r,e){return Array.isArray(e)?e.length===0?o`false`:o`${r} in ${e.map(t=>K(t,r))}`:o`${r} in ${K(e,r)}`}function Yr(r,e){return Array.isArray(e)?e.length===0?o`true`:o`${r} not in ${e.map(t=>K(t,r))}`:o`${r} not in ${K(e,r)}`}function Gr(r){return o`${r} is null`}function Zr(r){return o`${r} is not null`}function Xr(r){return o`exists ${r}`}function es(r){return o`not exists ${r}`}function ts(r,e,t){return o`${r} between ${K(e,r)} and ${K(t,r)}`}function rs(r,e,t){return o`${r} not between ${K(e,r)} and ${K(t,r)}`}function ss(r,e){return o`${r} like ${e}`}function is(r,e){return o`${r} not like ${e}`}function ns(r,e){return o`${r} ilike ${e}`}function os(r,e){return o`${r} not ilike ${e}`}function as(r){return o`${r} asc`}function ls(r){return o`${r} desc`}var ke=class{constructor(e,t,s){this.sourceTable=e,this.referencedTable=t,this.relationName=s,this.referencedTableName=t[h.Symbol.Name]}static[l]="Relation";referencedTableName;fieldName},Et=class{constructor(e,t){this.table=e,this.config=t}static[l]="Relations"},ie=class r extends ke{constructor(e,t,s,i){super(e,t,s?.relationName),this.config=s,this.isNullable=i}static[l]="One";withFieldName(e){let t=new r(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}},$e=class r extends ke{constructor(e,t,s){super(e,t,s?.relationName),this.config=s}static[l]="Many";withFieldName(e){let t=new r(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}};function us(){return{and:te,between:ts,eq:M,exists:Xr,gt:Jr,gte:kr,ilike:ns,inArray:Je,isNull:Gr,isNotNull:Zr,like:ss,lt:Wr,lte:Hr,ne:zr,not:Ur,notBetween:rs,notExists:es,notLike:is,notIlike:os,notInArray:Yr,or:Vr,sql:o}}function cs(){return{sql:o,asc:as,desc:ls}}function ms(r,e){Object.keys(r).length===1&&"default"in r&&!m(r.default,h)&&(r=r.default);let t={},s={},i={};for(let[n,a]of Object.entries(r))if(m(a,h)){let u=oe(a),f=s[u];t[u]=n,i[n]={tsName:n,dbName:a[h.Symbol.Name],schema:a[h.Symbol.Schema],columns:a[h.Symbol.Columns],relations:f?.relations??{},primaryKey:f?.primaryKey??[]};for(let c of Object.values(a[h.Symbol.Columns]))c.primary&&i[n].primaryKey.push(c);let d=a[h.Symbol.ExtraConfigBuilder]?.(a[h.Symbol.ExtraConfigColumns]);if(d)for(let c of Object.values(d))m(c,Ue)&&i[n].primaryKey.push(...c.columns)}else if(m(a,Et)){let u=oe(a.table),f=t[u],d=a.config(e(a.table)),c;for(let[y,b]of Object.entries(d))if(f){let N=i[f];N.relations[y]=b,c&&N.primaryKey.push(...c)}else u in s||(s[u]={relations:{},primaryKey:c}),s[u].relations[y]=b}return{tables:i,tableNamesMap:t}}function Ks(r){return function(t,s){return new ie(r,t,s,s?.fields.reduce((i,n)=>i&&n.notNull,!0)??!1)}}function Fs(r){return function(t,s){return new $e(r,t,s)}}function fs(r,e,t){if(m(t,ie)&&t.config)return{fields:t.config.fields,references:t.config.references};let s=e[oe(t.referencedTable)];if(!s)throw new Error(`Table "${t.referencedTable[h.Symbol.Name]}" not found in schema`);let i=r[s];if(!i)throw new Error(`Table "${s}" not found in schema`);let n=t.sourceTable,a=e[oe(n)];if(!a)throw new Error(`Table "${n[h.Symbol.Name]}" not found in schema`);let u=[];for(let f of Object.values(i.relations))(t.relationName&&t!==f&&f.relationName===t.relationName||!t.relationName&&f.referencedTable===t.sourceTable)&&u.push(f);if(u.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${s}"`):new Error(`There are multiple relations between "${s}" and "${t.sourceTable[h.Symbol.Name]}". Please specify relation name`);if(u[0]&&m(u[0],ie)&&u[0].config)return{fields:u[0].config.references,references:u[0].config.fields};throw new Error(`There is not enough information to infer relation "${a}.${t.fieldName}"`)}function hs(r){return{one:Ks(r),many:Fs(r)}}function We(r,e,t,s,i=n=>n){let n={};for(let[a,u]of s.entries())if(u.isJson){let f=e.relations[u.tsKey],d=t[a],c=typeof d=="string"?JSON.parse(d):d;n[u.tsKey]=m(f,ie)?c&&We(r,r[u.relationTableTsKey],c,u.selection,i):c.map(y=>We(r,r[u.relationTableTsKey],y,u.selection,i))}else{let f=i(t[a]),d=u.field,c;m(d,w)?c=d:m(d,p)?c=d.decoder:c=d.sql.decoder,n[u.tsKey]=f===null?null:c.mapFromDriverValue(f)}return n}var le=class{constructor(e){this.table=e}static[l]="ColumnAliasProxyHandler";get(e,t){return t==="table"?this.table:e[t]}},ye=class{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[l]="TableAliasProxyHandler";get(e,t){if(t===h.Symbol.IsAlias)return!0;if(t===h.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===h.Symbol.OriginalName)return this.alias;if(t===T)return{...e[T],name:this.alias,isAlias:!0};if(t===h.Symbol.Columns){let i=e[h.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map(a=>{n[a]=new Proxy(i[a],new le(new Proxy(e,this)))}),n}let s=e[t];return m(s,w)?new Proxy(s,new le(new Proxy(e,this))):s}},ds=class{constructor(e){this.alias=e}static[l]="RelationTableAliasProxyHandler";get(e,t){return t==="sourceTable"?qe(e.sourceTable,this.alias):e[t]}};function qe(r,e){return new Proxy(r,new ye(e,!1))}function G(r,e){return new Proxy(r,new le(new Proxy(r.table,new ye(e,!1))))}function jt(r,e){return new p.Aliased(ve(r.sql,e),r.fieldAlias)}function ve(r,e){return o.join(r.queryChunks.map(t=>m(t,w)?G(t,e):m(t,p)?ve(t,e):m(t,p.Aliased)?jt(t,e):t))}var P=class r{static[l]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===T)return{...e[T],selectedFields:new Proxy(e[T].selectedFields,this)};if(typeof t=="symbol")return e[t];let i=(m(e,O)?e._.selectedFields:m(e,I)?e[T].selectedFields:e)[t];if(m(i,p.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(m(i,p)){if(this.config.sqlBehavior==="sql")return i;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return m(i,w)?this.config.alias?new Proxy(i,new le(new Proxy(i.table,new ye(this.config.alias,this.config.replaceOriginalName??!1)))):i:typeof i!="object"||i===null?i:new Proxy(i,new r(this.config))}};var _=class{static[l]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}};var He=class{static[l]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){this.reference=()=>{let{name:s,columns:i,foreignColumns:n}=e();return{name:s,columns:i,foreignTable:n[0].table,foreignColumns:n}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new _t(e,this)}},_t=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[l]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:s}=this.reference(),i=t.map(u=>u.name),n=s.map(u=>u.name),a=[this.table[j],...i,s[0].table[j],...n];return e??`${a.join("_")}_fk`}};function Kt(r,e){return`${r[j]}_${e.join("_")}_unique`}var Dt=class{constructor(e,t){this.name=t,this.columns=e}static[l]="SQLiteUniqueConstraintBuilder";columns;build(e){return new Rt(e,this.columns,this.name)}},ps=class{static[l]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new Dt(e,this.name)}},Rt=class{constructor(e,t,s){this.table=e,this.columns=t,this.name=s??Kt(this.table,this.columns.map(i=>i.name))}static[l]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}};var E=class extends he{static[l]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:s,actions:i})=>((n,a)=>{let u=new He(()=>{let f=n();return{columns:[e],foreignColumns:[f]}});return a.onUpdate&&u.onUpdate(a.onUpdate),a.onDelete&&u.onDelete(a.onDelete),u.build(t)})(s,i))}},$=class extends w{constructor(e,t){t.uniqueName||(t.uniqueName=Kt(e,[t.name])),super(e,t),this.table=e}static[l]="SQLiteColumn"};var Ft=class extends E{static[l]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new It(e,this.config)}},It=class extends ${static[l]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(At.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}},Mt=class extends E{static[l]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new zt(e,this.config)}},zt=class extends ${static[l]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(At.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}},Vt=class extends E{static[l]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new Ut(e,this.config)}},Ut=class extends ${static[l]="SQLiteBlobBuffer";mapFromDriverValue(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}getSQLType(){return"blob"}};function ys(r,e){let{name:t,config:s}=Y(r,e);return s?.mode==="json"?new Mt(t):s?.mode==="bigint"?new Ft(t):new Vt(t)}var Jt=class extends E{static[l]="SQLiteCustomColumnBuilder";constructor(e,t,s){super(e,"custom","SQLiteCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=s}build(e){return new kt(e,this.config)}},kt=class extends ${static[l]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom=="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo=="function"?this.mapTo(e):e}};function gs(r){return(e,t)=>{let{name:s,config:i}=Y(e,t);return new Jt(s,i,r)}}var Qe=class extends E{static[l]="SQLiteBaseIntegerBuilder";constructor(e,t,s){super(e,t,s),this.config.autoIncrement=!1}primaryKey(e){return e?.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}},Le=class extends ${static[l]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}},Wt=class extends Qe{static[l]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new Ht(e,this.config)}},Ht=class extends Le{static[l]="SQLiteInteger"},Yt=class extends Qe{static[l]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp"),this.config.mode=t}defaultNow(){return this.default(o`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new Gt(e,this.config)}},Gt=class extends Le{static[l]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){return this.config.mode==="timestamp"?new Date(e*1e3):new Date(e)}mapToDriverValue(e){let t=e.getTime();return this.config.mode==="timestamp"?Math.floor(t/1e3):t}},Zt=class extends Qe{static[l]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean"),this.config.mode=t}build(e){return new Xt(e,this.config)}},Xt=class extends Le{static[l]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}};function Ye(r,e){let{name:t,config:s}=Y(r,e);return s?.mode==="timestamp"||s?.mode==="timestamp_ms"?new Yt(t,s.mode):s?.mode==="boolean"?new Zt(t,s.mode):new Wt(t)}var er=class extends E{static[l]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new tr(e,this.config)}},tr=class extends ${static[l]="SQLiteNumeric";mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return"numeric"}},rr=class extends E{static[l]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new sr(e,this.config)}},sr=class extends ${static[l]="SQLiteNumericNumber";mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}},ir=class extends E{static[l]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new nr(e,this.config)}},nr=class extends ${static[l]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}};function bs(r,e){let{name:t,config:s}=Y(r,e),i=s?.mode;return i==="number"?new rr(t):i==="bigint"?new ir(t):new er(t)}var or=class extends E{static[l]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new ar(e,this.config)}},ar=class extends ${static[l]="SQLiteReal";getSQLType(){return"real"}};function Ss(r){return new or(r??"")}var lr=class extends E{static[l]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText"),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new ur(e,this.config)}},ur=class extends ${static[l]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}},cr=class extends E{static[l]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new mr(e,this.config)}},mr=class extends ${static[l]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}};function U(r,e={}){let{name:t,config:s}=Y(r,e);return s.mode==="json"?new cr(t):new lr(t,s)}function ws(){return{blob:ys,customType:gs,integer:Ye,numeric:bs,real:Ss,text:U}}var fr=Symbol.for("drizzle:SQLiteInlineForeignKeys"),B=class extends h{static[l]="SQLiteTable";static Symbol=Object.assign({},h.Symbol,{InlineForeignKeys:fr});[h.Symbol.Columns];[fr]=[];[h.Symbol.ExtraConfigBuilder]=void 0};function Is(r,e,t,s,i=r){let n=new B(r,s,i),a=typeof e=="function"?e(ws()):e,u=Object.fromEntries(Object.entries(a).map(([d,c])=>{let y=c;y.setName(d);let b=y.build(n);return n[fr].push(...y.buildForeignKeys(b,n)),[d,b]})),f=Object.assign(n,u);return f[h.Symbol.Columns]=u,f[h.Symbol.ExtraConfigColumns]=u,t&&(f[B.Symbol.ExtraConfigBuilder]=t),f}var xs=(r,e,t)=>Is(r,e,t);function Cs(...r){return r[0].columns?new Ge(r[0].columns,r[0].name):new Ge(r)}var Ge=class{static[l]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new hr(e,this.columns,this.name)}},hr=class{constructor(e,t,s){this.table=e,this.columns=t,this.name=s}static[l]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[B.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}};function W(r){return m(r,B)?[`${r[h.Symbol.BaseName]}`]:m(r,O)?r._.usedTables??[]:m(r,p)?r.usedTables??[]:[]}var Oe=class extends _{constructor(e,t,s,i){super(),this.table=e,this.session=t,this.dialect=s,this.config={table:e,withList:i}}static[l]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.table[h.Symbol.Columns],new P({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),s=Array.isArray(t)?t:[t];this.config.orderBy=s}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[B.Symbol.Columns]){return this.config.returning=V(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:W(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}};function Ms(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(t=>t.toLowerCase()).join("_")}function zs(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,s,i)=>{let n=i===0?s.toLowerCase():`${s[0].toUpperCase()}${s.slice(1)}`;return t+n},"")}function Vs(r){return r}var Ze=class{static[l]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Ms:e==="camelCase"?zs:Vs}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[h.Symbol.Schema]??"public",s=e.table[h.Symbol.OriginalName],i=`${t}.${s}.${e.name}`;return this.cache[i]||this.cacheTable(e.table),this.cache[i]}cacheTable(e){let t=e[h.Symbol.Schema]??"public",s=e[h.Symbol.OriginalName],i=`${t}.${s}`;if(!this.cachedTables[i]){for(let n of Object.values(e[h.Symbol.Columns])){let a=`${i}.${n.name}`;this.cache[a]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}};var ue=class extends Error{static[l]="DrizzleError";constructor({message:e,cause:t}){super(e),this.name="DrizzleError",this.cause=t}},re=class r extends Error{constructor(e,t,s){super(`Failed query: ${e}
2
- params: ${t}`),this.query=e,this.params=t,this.cause=s,Error.captureStackTrace(this,r),s&&(this.cause=s)}},Xe=class extends ue{static[l]="TransactionRollbackError";constructor(){super({message:"Rollback"})}};var ne=class extends I{static[l]="SQLiteViewBase"};var ce=class{static[l]="SQLiteDialect";casing;constructor(e){this.casing=new Ze(e?.casing)}escapeName(e){return`"${e}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[o`with `];for(let[s,i]of e.entries())t.push(o`${o.identifier(i._.alias)} as (${i._.sql})`),s<e.length-1&&t.push(o`, `);return t.push(o` `),o.join(t)}buildDeleteQuery({table:e,where:t,returning:s,withList:i,limit:n,orderBy:a}){let u=this.buildWithCTE(i),f=s?o` returning ${this.buildSelection(s,{isSingleTable:!0})}`:void 0,d=t?o` where ${t}`:void 0,c=this.buildOrderBy(a),y=this.buildLimit(n);return o`${u}delete from ${e}${d}${f}${c}${y}`}buildUpdateSet(e,t){let s=e[h.Symbol.Columns],i=Object.keys(s).filter(a=>t[a]!==void 0||s[a]?.onUpdateFn!==void 0),n=i.length;return o.join(i.flatMap((a,u)=>{let f=s[a],d=t[a]??o.param(f.onUpdateFn(),f),c=o`${o.identifier(this.casing.getColumnCasing(f))} = ${d}`;return u<n-1?[c,o.raw(", ")]:[c]}))}buildUpdateQuery({table:e,set:t,where:s,returning:i,withList:n,joins:a,from:u,limit:f,orderBy:d}){let c=this.buildWithCTE(n),y=this.buildUpdateSet(e,t),b=u&&o.join([o.raw(" from "),this.buildFromTable(u)]),N=this.buildJoins(a),v=i?o` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,S=s?o` where ${s}`:void 0,Q=this.buildOrderBy(d),L=this.buildLimit(f);return o`${c}update ${e} set ${y}${b}${N}${S}${v}${Q}${L}`}buildSelection(e,{isSingleTable:t=!1}={}){let s=e.length,i=e.flatMap(({field:n},a)=>{let u=[];if(m(n,p.Aliased)&&n.isSelectionField)u.push(o.identifier(n.fieldAlias));else if(m(n,p.Aliased)||m(n,p)){let f=m(n,p.Aliased)?n.sql:n;t?u.push(new p(f.queryChunks.map(d=>m(d,w)?o.identifier(this.casing.getColumnCasing(d)):d))):u.push(f),m(n,p.Aliased)&&u.push(o` as ${o.identifier(n.fieldAlias)}`)}else if(m(n,w)){let f=n.table[h.Symbol.Name];n.columnType==="SQLiteNumericBigInt"?t?u.push(o`cast(${o.identifier(this.casing.getColumnCasing(n))} as text)`):u.push(o`cast(${o.identifier(f)}.${o.identifier(this.casing.getColumnCasing(n))} as text)`):t?u.push(o.identifier(this.casing.getColumnCasing(n))):u.push(o`${o.identifier(f)}.${o.identifier(this.casing.getColumnCasing(n))}`)}return a<s-1&&u.push(o`, `),u});return o.join(i)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[s,i]of e.entries()){s===0&&t.push(o` `);let n=i.table,a=i.on?o` on ${i.on}`:void 0;if(m(n,B)){let u=n[B.Symbol.Name],f=n[B.Symbol.Schema],d=n[B.Symbol.OriginalName],c=u===d?void 0:i.alias;t.push(o`${o.raw(i.joinType)} join ${f?o`${o.identifier(f)}.`:void 0}${o.identifier(d)}${c&&o` ${o.identifier(c)}`}${a}`)}else t.push(o`${o.raw(i.joinType)} join ${n}${a}`);s<e.length-1&&t.push(o` `)}return o.join(t)}buildLimit(e){return typeof e=="object"||typeof e=="number"&&e>=0?o` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e)for(let[s,i]of e.entries())t.push(i),s<e.length-1&&t.push(o`, `);return t.length>0?o` order by ${o.join(t)}`:void 0}buildFromTable(e){return m(e,h)&&e[h.Symbol.IsAlias]?o`${o`${o.identifier(e[h.Symbol.Schema]??"")}.`.if(e[h.Symbol.Schema])}${o.identifier(e[h.Symbol.OriginalName])} ${o.identifier(e[h.Symbol.Name])}`:e}buildSelectQuery({withList:e,fields:t,fieldsFlat:s,where:i,having:n,table:a,joins:u,orderBy:f,groupBy:d,limit:c,offset:y,distinct:b,setOperators:N}){let v=s??V(t);for(let k of v)if(m(k.field,w)&&se(k.field.table)!==(m(a,O)?a._.alias:m(a,ne)?a[T].name:m(a,p)?void 0:se(a))&&!(H=>u?.some(({alias:je})=>je===(H[h.Symbol.IsAlias]?se(H):H[h.Symbol.BaseName])))(k.field.table)){let H=se(k.field.table);throw new Error(`Your "${k.path.join("->")}" field references a column "${H}"."${k.field.name}", but the table "${H}" is not part of the query! Did you forget to join it?`)}let S=!u||u.length===0,Q=this.buildWithCTE(e),L=b?o` distinct`:void 0,F=this.buildSelection(v,{isSingleTable:S}),D=this.buildFromTable(a),x=this.buildJoins(u),Z=i?o` where ${i}`:void 0,z=n?o` having ${n}`:void 0,g=[];if(d)for(let[k,H]of d.entries())g.push(H),k<d.length-1&&g.push(o`, `);let C=g.length>0?o` group by ${o.join(g)}`:void 0,X=this.buildOrderBy(f),Ee=this.buildLimit(c),dt=y?o` offset ${y}`:void 0,fe=o`${Q}select${L} ${F} from ${D}${x}${Z}${C}${z}${X}${Ee}${dt}`;return N.length>0?this.buildSetOperations(fe,N):fe}buildSetOperations(e,t){let[s,...i]=t;if(!s)throw new Error("Cannot pass undefined values to any set operator");return i.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:s}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:s}),i)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:s,rightSelect:i,limit:n,orderBy:a,offset:u}}){let f=o`${e.getSQL()} `,d=o`${i.getSQL()}`,c;if(a&&a.length>0){let v=[];for(let S of a)if(m(S,$))v.push(o.identifier(S.name));else if(m(S,p)){for(let Q=0;Q<S.queryChunks.length;Q++){let L=S.queryChunks[Q];m(L,$)&&(S.queryChunks[Q]=o.identifier(this.casing.getColumnCasing(L)))}v.push(o`${S}`)}else v.push(o`${S}`);c=o` order by ${o.join(v,o`, `)}`}let y=typeof n=="object"||typeof n=="number"&&n>=0?o` limit ${n}`:void 0,b=o.raw(`${t} ${s?"all ":""}`),N=u?o` offset ${u}`:void 0;return o`${f}${b}${d}${c}${y}${N}`}buildInsertQuery({table:e,values:t,onConflict:s,returning:i,withList:n,select:a}){let u=[],f=e[h.Symbol.Columns],d=Object.entries(f).filter(([S,Q])=>!Q.shouldDisableInsert()),c=d.map(([,S])=>o.identifier(this.casing.getColumnCasing(S)));if(a){let S=t;m(S,p)?u.push(S):u.push(S.getSQL())}else{let S=t;u.push(o.raw("values "));for(let[Q,L]of S.entries()){let F=[];for(let[D,x]of d){let Z=L[D];if(Z===void 0||m(Z,R)&&Z.value===void 0){let z;if(x.default!==null&&x.default!==void 0)z=m(x.default,p)?x.default:o.param(x.default,x);else if(x.defaultFn!==void 0){let g=x.defaultFn();z=m(g,p)?g:o.param(g,x)}else if(!x.default&&x.onUpdateFn!==void 0){let g=x.onUpdateFn();z=m(g,p)?g:o.param(g,x)}else z=o`null`;F.push(z)}else F.push(Z)}u.push(F),Q<S.length-1&&u.push(o`, `)}}let y=this.buildWithCTE(n),b=o.join(u),N=i?o` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,v=s?.length?o.join(s):void 0;return o`${y}insert into ${e} ${c} ${b}${v}${N}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:s,table:i,tableConfig:n,queryConfig:a,tableAlias:u,nestedQueryRelation:f,joinOn:d}){let c=[],y,b,N=[],v,S=[];if(a===!0)c=Object.entries(n.columns).map(([F,D])=>({dbKey:D.name,tsKey:F,field:G(D,u),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let L=Object.fromEntries(Object.entries(n.columns).map(([g,C])=>[g,G(C,u)]));if(a.where){let g=typeof a.where=="function"?a.where(L,us()):a.where;v=g&&ve(g,u)}let F=[],D=[];if(a.columns){let g=!1;for(let[C,X]of Object.entries(a.columns))X!==void 0&&C in n.columns&&(!g&&X===!0&&(g=!0),D.push(C));D.length>0&&(D=g?D.filter(C=>a.columns?.[C]===!0):Object.keys(n.columns).filter(C=>!D.includes(C)))}else D=Object.keys(n.columns);for(let g of D){let C=n.columns[g];F.push({tsKey:g,value:C})}let x=[];a.with&&(x=Object.entries(a.with).filter(g=>!!g[1]).map(([g,C])=>({tsKey:g,queryConfig:C,relation:n.relations[g]})));let Z;if(a.extras){Z=typeof a.extras=="function"?a.extras(L,{sql:o}):a.extras;for(let[g,C]of Object.entries(Z))F.push({tsKey:g,value:jt(C,u)})}for(let{tsKey:g,value:C}of F)c.push({dbKey:m(C,p.Aliased)?C.fieldAlias:n.columns[g].name,tsKey:g,field:m(C,w)?G(C,u):C,relationTableTsKey:void 0,isJson:!1,selection:[]});let z=typeof a.orderBy=="function"?a.orderBy(L,cs()):a.orderBy??[];Array.isArray(z)||(z=[z]),N=z.map(g=>m(g,w)?G(g,u):ve(g,u)),y=a.limit,b=a.offset;for(let{tsKey:g,queryConfig:C,relation:X}of x){let Ee=fs(t,s,X),dt=oe(X.referencedTable),fe=s[dt],k=`${u}_${g}`,H=te(...Ee.fields.map((As,Ps)=>M(G(Ee.references[Ps],k),G(As,u)))),je=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:s,table:e[fe],tableConfig:t[fe],queryConfig:m(X,ie)?C===!0?{limit:1}:{...C,limit:1}:C,tableAlias:k,joinOn:H,nestedQueryRelation:X}),Bs=o`(${je.sql})`.as(g);c.push({dbKey:g,tsKey:g,field:Bs,relationTableTsKey:fe,isJson:!0,selection:je.selection})}}if(c.length===0)throw new ue({message:`No fields selected for table "${n.tsName}" ("${u}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let Q;if(v=te(d,v),f){let L=o`json_array(${o.join(c.map(({field:x})=>m(x,$)?o.identifier(this.casing.getColumnCasing(x)):m(x,p.Aliased)?x.sql:x),o`, `)})`;m(f,$e)&&(L=o`coalesce(json_group_array(${L}), json_array())`);let F=[{dbKey:"data",tsKey:"data",field:L.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:c}];y!==void 0||b!==void 0||N.length>0?(Q=this.buildSelectQuery({table:qe(i,u),fields:{},fieldsFlat:[{path:[],field:o.raw("*")}],where:v,limit:y,offset:b,orderBy:N,setOperators:[]}),v=void 0,y=void 0,b=void 0,N=void 0):Q=qe(i,u),Q=this.buildSelectQuery({table:m(Q,B)?Q:new O(Q,{},u),fields:{},fieldsFlat:F.map(({field:x})=>({path:[],field:m(x,w)?G(x,u):x})),joins:S,where:v,limit:y,offset:b,orderBy:N,setOperators:[]})}else Q=this.buildSelectQuery({table:qe(i,u),fields:{},fieldsFlat:c.map(({field:L})=>({path:[],field:m(L,w)?G(L,u):L})),joins:S,where:v,limit:y,offset:b,orderBy:N,setOperators:[]});return{tableTsKey:n.tsName,sql:Q,selection:c}}},ge=class extends ce{static[l]="SQLiteSyncDialect";migrate(e,t,s){let i=s===void 0||typeof s=="string"?"__drizzle_migrations":s.migrationsTable??"__drizzle_migrations",n=o`
3
- CREATE TABLE IF NOT EXISTS ${o.identifier(i)} (
1
+ import { DurableObject } from "cloudflare:workers";
2
+
3
+ //#region rolldown:runtime
4
+ var __defProp = Object.defineProperty;
5
+ var __export = (all) => {
6
+ let target = {};
7
+ for (var name in all) __defProp(target, name, {
8
+ get: all[name],
9
+ enumerable: true
10
+ });
11
+ return target;
12
+ };
13
+
14
+ //#endregion
15
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/entity.js
16
+ const entityKind = Symbol.for("drizzle:entityKind");
17
+ const hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
18
+ function is(value, type) {
19
+ if (!value || typeof value !== "object") return false;
20
+ if (value instanceof type) return true;
21
+ if (!Object.prototype.hasOwnProperty.call(type, entityKind)) throw new Error(`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);
22
+ let cls = Object.getPrototypeOf(value).constructor;
23
+ if (cls) while (cls) {
24
+ if (entityKind in cls && cls[entityKind] === type[entityKind]) return true;
25
+ cls = Object.getPrototypeOf(cls);
26
+ }
27
+ return false;
28
+ }
29
+
30
+ //#endregion
31
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/logger.js
32
+ var ConsoleLogWriter = class {
33
+ static [entityKind] = "ConsoleLogWriter";
34
+ write(message) {
35
+ console.log(message);
36
+ }
37
+ };
38
+ var DefaultLogger = class {
39
+ static [entityKind] = "DefaultLogger";
40
+ writer;
41
+ constructor(config) {
42
+ this.writer = config?.writer ?? new ConsoleLogWriter();
43
+ }
44
+ logQuery(query, params) {
45
+ const stringifiedParams = params.map((p) => {
46
+ try {
47
+ return JSON.stringify(p);
48
+ } catch {
49
+ return String(p);
50
+ }
51
+ });
52
+ const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
53
+ this.writer.write(`Query: ${query}${paramsStr}`);
54
+ }
55
+ };
56
+ var NoopLogger = class {
57
+ static [entityKind] = "NoopLogger";
58
+ logQuery() {}
59
+ };
60
+
61
+ //#endregion
62
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/table.utils.js
63
+ const TableName = Symbol.for("drizzle:Name");
64
+
65
+ //#endregion
66
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/table.js
67
+ const Schema = Symbol.for("drizzle:Schema");
68
+ const Columns = Symbol.for("drizzle:Columns");
69
+ const ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
70
+ const OriginalName = Symbol.for("drizzle:OriginalName");
71
+ const BaseName = Symbol.for("drizzle:BaseName");
72
+ const IsAlias = Symbol.for("drizzle:IsAlias");
73
+ const ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
74
+ const IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
75
+ var Table = class {
76
+ static [entityKind] = "Table";
77
+ /** @internal */
78
+ static Symbol = {
79
+ Name: TableName,
80
+ Schema,
81
+ OriginalName,
82
+ Columns,
83
+ ExtraConfigColumns,
84
+ BaseName,
85
+ IsAlias,
86
+ ExtraConfigBuilder
87
+ };
88
+ /**
89
+ * @internal
90
+ * Can be changed if the table is aliased.
91
+ */
92
+ [TableName];
93
+ /**
94
+ * @internal
95
+ * Used to store the original name of the table, before any aliasing.
96
+ */
97
+ [OriginalName];
98
+ /** @internal */
99
+ [Schema];
100
+ /** @internal */
101
+ [Columns];
102
+ /** @internal */
103
+ [ExtraConfigColumns];
104
+ /**
105
+ * @internal
106
+ * Used to store the table name before the transformation via the `tableCreator` functions.
107
+ */
108
+ [BaseName];
109
+ /** @internal */
110
+ [IsAlias] = false;
111
+ /** @internal */
112
+ [IsDrizzleTable] = true;
113
+ /** @internal */
114
+ [ExtraConfigBuilder] = void 0;
115
+ constructor(name, schema, baseName) {
116
+ this[TableName] = this[OriginalName] = name;
117
+ this[Schema] = schema;
118
+ this[BaseName] = baseName;
119
+ }
120
+ };
121
+ function getTableName(table) {
122
+ return table[TableName];
123
+ }
124
+ function getTableUniqueName(table) {
125
+ return `${table[Schema] ?? "public"}.${table[TableName]}`;
126
+ }
127
+
128
+ //#endregion
129
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/column.js
130
+ var Column = class {
131
+ constructor(table, config) {
132
+ this.table = table;
133
+ this.config = config;
134
+ this.name = config.name;
135
+ this.keyAsName = config.keyAsName;
136
+ this.notNull = config.notNull;
137
+ this.default = config.default;
138
+ this.defaultFn = config.defaultFn;
139
+ this.onUpdateFn = config.onUpdateFn;
140
+ this.hasDefault = config.hasDefault;
141
+ this.primary = config.primaryKey;
142
+ this.isUnique = config.isUnique;
143
+ this.uniqueName = config.uniqueName;
144
+ this.uniqueType = config.uniqueType;
145
+ this.dataType = config.dataType;
146
+ this.columnType = config.columnType;
147
+ this.generated = config.generated;
148
+ this.generatedIdentity = config.generatedIdentity;
149
+ }
150
+ static [entityKind] = "Column";
151
+ name;
152
+ keyAsName;
153
+ primary;
154
+ notNull;
155
+ default;
156
+ defaultFn;
157
+ onUpdateFn;
158
+ hasDefault;
159
+ isUnique;
160
+ uniqueName;
161
+ uniqueType;
162
+ dataType;
163
+ columnType;
164
+ enumValues = void 0;
165
+ generated = void 0;
166
+ generatedIdentity = void 0;
167
+ config;
168
+ mapFromDriverValue(value) {
169
+ return value;
170
+ }
171
+ mapToDriverValue(value) {
172
+ return value;
173
+ }
174
+ shouldDisableInsert() {
175
+ return this.config.generated !== void 0 && this.config.generated.type !== "byDefault";
176
+ }
177
+ };
178
+
179
+ //#endregion
180
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/column-builder.js
181
+ var ColumnBuilder = class {
182
+ static [entityKind] = "ColumnBuilder";
183
+ config;
184
+ constructor(name, dataType, columnType) {
185
+ this.config = {
186
+ name,
187
+ keyAsName: name === "",
188
+ notNull: false,
189
+ default: void 0,
190
+ hasDefault: false,
191
+ primaryKey: false,
192
+ isUnique: false,
193
+ uniqueName: void 0,
194
+ uniqueType: void 0,
195
+ dataType,
196
+ columnType,
197
+ generated: void 0
198
+ };
199
+ }
200
+ /**
201
+ * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * const users = pgTable('users', {
206
+ * id: integer('id').$type<UserId>().primaryKey(),
207
+ * details: json('details').$type<UserDetails>().notNull(),
208
+ * });
209
+ * ```
210
+ */
211
+ $type() {
212
+ return this;
213
+ }
214
+ /**
215
+ * Adds a `not null` clause to the column definition.
216
+ *
217
+ * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
218
+ */
219
+ notNull() {
220
+ this.config.notNull = true;
221
+ return this;
222
+ }
223
+ /**
224
+ * Adds a `default <value>` clause to the column definition.
225
+ *
226
+ * Affects the `insert` model of the table - columns *with* `default` are optional on insert.
227
+ *
228
+ * If you need to set a dynamic default value, use {@link $defaultFn} instead.
229
+ */
230
+ default(value) {
231
+ this.config.default = value;
232
+ this.config.hasDefault = true;
233
+ return this;
234
+ }
235
+ /**
236
+ * Adds a dynamic default value to the column.
237
+ * The function will be called when the row is inserted, and the returned value will be used as the column value.
238
+ *
239
+ * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
240
+ */
241
+ $defaultFn(fn) {
242
+ this.config.defaultFn = fn;
243
+ this.config.hasDefault = true;
244
+ return this;
245
+ }
246
+ /**
247
+ * Alias for {@link $defaultFn}.
248
+ */
249
+ $default = this.$defaultFn;
250
+ /**
251
+ * Adds a dynamic update value to the column.
252
+ * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.
253
+ * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.
254
+ *
255
+ * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
256
+ */
257
+ $onUpdateFn(fn) {
258
+ this.config.onUpdateFn = fn;
259
+ this.config.hasDefault = true;
260
+ return this;
261
+ }
262
+ /**
263
+ * Alias for {@link $onUpdateFn}.
264
+ */
265
+ $onUpdate = this.$onUpdateFn;
266
+ /**
267
+ * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
268
+ *
269
+ * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
270
+ */
271
+ primaryKey() {
272
+ this.config.primaryKey = true;
273
+ this.config.notNull = true;
274
+ return this;
275
+ }
276
+ /** @internal Sets the name of the column to the key within the table definition if a name was not given. */
277
+ setName(name) {
278
+ if (this.config.name !== "") return;
279
+ this.config.name = name;
280
+ }
281
+ };
282
+
283
+ //#endregion
284
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/pg-core/foreign-keys.js
285
+ var ForeignKeyBuilder$1 = class {
286
+ static [entityKind] = "PgForeignKeyBuilder";
287
+ /** @internal */
288
+ reference;
289
+ /** @internal */
290
+ _onUpdate = "no action";
291
+ /** @internal */
292
+ _onDelete = "no action";
293
+ constructor(config, actions) {
294
+ this.reference = () => {
295
+ const { name, columns: columns$1, foreignColumns } = config();
296
+ return {
297
+ name,
298
+ columns: columns$1,
299
+ foreignTable: foreignColumns[0].table,
300
+ foreignColumns
301
+ };
302
+ };
303
+ if (actions) {
304
+ this._onUpdate = actions.onUpdate;
305
+ this._onDelete = actions.onDelete;
306
+ }
307
+ }
308
+ onUpdate(action) {
309
+ this._onUpdate = action === void 0 ? "no action" : action;
310
+ return this;
311
+ }
312
+ onDelete(action) {
313
+ this._onDelete = action === void 0 ? "no action" : action;
314
+ return this;
315
+ }
316
+ /** @internal */
317
+ build(table) {
318
+ return new ForeignKey$1(table, this);
319
+ }
320
+ };
321
+ var ForeignKey$1 = class {
322
+ constructor(table, builder) {
323
+ this.table = table;
324
+ this.reference = builder.reference;
325
+ this.onUpdate = builder._onUpdate;
326
+ this.onDelete = builder._onDelete;
327
+ }
328
+ static [entityKind] = "PgForeignKey";
329
+ reference;
330
+ onUpdate;
331
+ onDelete;
332
+ getName() {
333
+ const { name, columns: columns$1, foreignColumns } = this.reference();
334
+ const columnNames = columns$1.map((column) => column.name);
335
+ const foreignColumnNames = foreignColumns.map((column) => column.name);
336
+ const chunks = [
337
+ this.table[TableName],
338
+ ...columnNames,
339
+ foreignColumns[0].table[TableName],
340
+ ...foreignColumnNames
341
+ ];
342
+ return name ?? `${chunks.join("_")}_fk`;
343
+ }
344
+ };
345
+
346
+ //#endregion
347
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/tracing-utils.js
348
+ function iife(fn, ...args) {
349
+ return fn(...args);
350
+ }
351
+
352
+ //#endregion
353
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/pg-core/unique-constraint.js
354
+ function uniqueKeyName$1(table, columns$1) {
355
+ return `${table[TableName]}_${columns$1.join("_")}_unique`;
356
+ }
357
+ var UniqueConstraintBuilder$1 = class {
358
+ constructor(columns$1, name) {
359
+ this.name = name;
360
+ this.columns = columns$1;
361
+ }
362
+ static [entityKind] = "PgUniqueConstraintBuilder";
363
+ /** @internal */
364
+ columns;
365
+ /** @internal */
366
+ nullsNotDistinctConfig = false;
367
+ nullsNotDistinct() {
368
+ this.nullsNotDistinctConfig = true;
369
+ return this;
370
+ }
371
+ /** @internal */
372
+ build(table) {
373
+ return new UniqueConstraint$1(table, this.columns, this.nullsNotDistinctConfig, this.name);
374
+ }
375
+ };
376
+ var UniqueOnConstraintBuilder$1 = class {
377
+ static [entityKind] = "PgUniqueOnConstraintBuilder";
378
+ /** @internal */
379
+ name;
380
+ constructor(name) {
381
+ this.name = name;
382
+ }
383
+ on(...columns$1) {
384
+ return new UniqueConstraintBuilder$1(columns$1, this.name);
385
+ }
386
+ };
387
+ var UniqueConstraint$1 = class {
388
+ constructor(table, columns$1, nullsNotDistinct, name) {
389
+ this.table = table;
390
+ this.columns = columns$1;
391
+ this.name = name ?? uniqueKeyName$1(this.table, this.columns.map((column) => column.name));
392
+ this.nullsNotDistinct = nullsNotDistinct;
393
+ }
394
+ static [entityKind] = "PgUniqueConstraint";
395
+ columns;
396
+ name;
397
+ nullsNotDistinct = false;
398
+ getName() {
399
+ return this.name;
400
+ }
401
+ };
402
+
403
+ //#endregion
404
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/pg-core/utils/array.js
405
+ function parsePgArrayValue(arrayString, startFrom, inQuotes) {
406
+ for (let i = startFrom; i < arrayString.length; i++) {
407
+ const char = arrayString[i];
408
+ if (char === "\\") {
409
+ i++;
410
+ continue;
411
+ }
412
+ if (char === "\"") return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1];
413
+ if (inQuotes) continue;
414
+ if (char === "," || char === "}") return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i];
415
+ }
416
+ return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length];
417
+ }
418
+ function parsePgNestedArray(arrayString, startFrom = 0) {
419
+ const result = [];
420
+ let i = startFrom;
421
+ let lastCharIsComma = false;
422
+ while (i < arrayString.length) {
423
+ const char = arrayString[i];
424
+ if (char === ",") {
425
+ if (lastCharIsComma || i === startFrom) result.push("");
426
+ lastCharIsComma = true;
427
+ i++;
428
+ continue;
429
+ }
430
+ lastCharIsComma = false;
431
+ if (char === "\\") {
432
+ i += 2;
433
+ continue;
434
+ }
435
+ if (char === "\"") {
436
+ const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);
437
+ result.push(value2);
438
+ i = startFrom2;
439
+ continue;
440
+ }
441
+ if (char === "}") return [result, i + 1];
442
+ if (char === "{") {
443
+ const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);
444
+ result.push(value2);
445
+ i = startFrom2;
446
+ continue;
447
+ }
448
+ const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
449
+ result.push(value);
450
+ i = newStartFrom;
451
+ }
452
+ return [result, i];
453
+ }
454
+ function parsePgArray(arrayString) {
455
+ const [result] = parsePgNestedArray(arrayString, 1);
456
+ return result;
457
+ }
458
+ function makePgArray(array) {
459
+ return `{${array.map((item) => {
460
+ if (Array.isArray(item)) return makePgArray(item);
461
+ if (typeof item === "string") return `"${item.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
462
+ return `${item}`;
463
+ }).join(",")}}`;
464
+ }
465
+
466
+ //#endregion
467
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/pg-core/columns/common.js
468
+ var PgColumnBuilder = class extends ColumnBuilder {
469
+ foreignKeyConfigs = [];
470
+ static [entityKind] = "PgColumnBuilder";
471
+ array(size) {
472
+ return new PgArrayBuilder(this.config.name, this, size);
473
+ }
474
+ references(ref, actions = {}) {
475
+ this.foreignKeyConfigs.push({
476
+ ref,
477
+ actions
478
+ });
479
+ return this;
480
+ }
481
+ unique(name, config) {
482
+ this.config.isUnique = true;
483
+ this.config.uniqueName = name;
484
+ this.config.uniqueType = config?.nulls;
485
+ return this;
486
+ }
487
+ generatedAlwaysAs(as) {
488
+ this.config.generated = {
489
+ as,
490
+ type: "always",
491
+ mode: "stored"
492
+ };
493
+ return this;
494
+ }
495
+ /** @internal */
496
+ buildForeignKeys(column, table) {
497
+ return this.foreignKeyConfigs.map(({ ref, actions }) => {
498
+ return iife((ref2, actions2) => {
499
+ const builder = new ForeignKeyBuilder$1(() => {
500
+ const foreignColumn = ref2();
501
+ return {
502
+ columns: [column],
503
+ foreignColumns: [foreignColumn]
504
+ };
505
+ });
506
+ if (actions2.onUpdate) builder.onUpdate(actions2.onUpdate);
507
+ if (actions2.onDelete) builder.onDelete(actions2.onDelete);
508
+ return builder.build(table);
509
+ }, ref, actions);
510
+ });
511
+ }
512
+ /** @internal */
513
+ buildExtraConfigColumn(table) {
514
+ return new ExtraConfigColumn(table, this.config);
515
+ }
516
+ };
517
+ var PgColumn = class extends Column {
518
+ constructor(table, config) {
519
+ if (!config.uniqueName) config.uniqueName = uniqueKeyName$1(table, [config.name]);
520
+ super(table, config);
521
+ this.table = table;
522
+ }
523
+ static [entityKind] = "PgColumn";
524
+ };
525
+ var ExtraConfigColumn = class extends PgColumn {
526
+ static [entityKind] = "ExtraConfigColumn";
527
+ getSQLType() {
528
+ return this.getSQLType();
529
+ }
530
+ indexConfig = {
531
+ order: this.config.order ?? "asc",
532
+ nulls: this.config.nulls ?? "last",
533
+ opClass: this.config.opClass
534
+ };
535
+ defaultConfig = {
536
+ order: "asc",
537
+ nulls: "last",
538
+ opClass: void 0
539
+ };
540
+ asc() {
541
+ this.indexConfig.order = "asc";
542
+ return this;
543
+ }
544
+ desc() {
545
+ this.indexConfig.order = "desc";
546
+ return this;
547
+ }
548
+ nullsFirst() {
549
+ this.indexConfig.nulls = "first";
550
+ return this;
551
+ }
552
+ nullsLast() {
553
+ this.indexConfig.nulls = "last";
554
+ return this;
555
+ }
556
+ /**
557
+ * ### PostgreSQL documentation quote
558
+ *
559
+ * > An operator class with optional parameters can be specified for each column of an index.
560
+ * The operator class identifies the operators to be used by the index for that column.
561
+ * For example, a B-tree index on four-byte integers would use the int4_ops class;
562
+ * this operator class includes comparison functions for four-byte integers.
563
+ * In practice the default operator class for the column's data type is usually sufficient.
564
+ * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.
565
+ * For example, we might want to sort a complex-number data type either by absolute value or by real part.
566
+ * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.
567
+ * More information about operator classes check:
568
+ *
569
+ * ### Useful links
570
+ * https://www.postgresql.org/docs/current/sql-createindex.html
571
+ *
572
+ * https://www.postgresql.org/docs/current/indexes-opclass.html
573
+ *
574
+ * https://www.postgresql.org/docs/current/xindex.html
575
+ *
576
+ * ### Additional types
577
+ * If you have the `pg_vector` extension installed in your database, you can use the
578
+ * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.
579
+ *
580
+ * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**
581
+ *
582
+ * @param opClass
583
+ * @returns
584
+ */
585
+ op(opClass) {
586
+ this.indexConfig.opClass = opClass;
587
+ return this;
588
+ }
589
+ };
590
+ var IndexedColumn = class {
591
+ static [entityKind] = "IndexedColumn";
592
+ constructor(name, keyAsName, type, indexConfig) {
593
+ this.name = name;
594
+ this.keyAsName = keyAsName;
595
+ this.type = type;
596
+ this.indexConfig = indexConfig;
597
+ }
598
+ name;
599
+ keyAsName;
600
+ type;
601
+ indexConfig;
602
+ };
603
+ var PgArrayBuilder = class extends PgColumnBuilder {
604
+ static [entityKind] = "PgArrayBuilder";
605
+ constructor(name, baseBuilder, size) {
606
+ super(name, "array", "PgArray");
607
+ this.config.baseBuilder = baseBuilder;
608
+ this.config.size = size;
609
+ }
610
+ /** @internal */
611
+ build(table) {
612
+ const baseColumn = this.config.baseBuilder.build(table);
613
+ return new PgArray(table, this.config, baseColumn);
614
+ }
615
+ };
616
+ var PgArray = class PgArray extends PgColumn {
617
+ constructor(table, config, baseColumn, range) {
618
+ super(table, config);
619
+ this.baseColumn = baseColumn;
620
+ this.range = range;
621
+ this.size = config.size;
622
+ }
623
+ size;
624
+ static [entityKind] = "PgArray";
625
+ getSQLType() {
626
+ return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`;
627
+ }
628
+ mapFromDriverValue(value) {
629
+ if (typeof value === "string") value = parsePgArray(value);
630
+ return value.map((v) => this.baseColumn.mapFromDriverValue(v));
631
+ }
632
+ mapToDriverValue(value, isNestedArray = false) {
633
+ const a = value.map((v) => v === null ? null : is(this.baseColumn, PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v));
634
+ if (isNestedArray) return a;
635
+ return makePgArray(a);
636
+ }
637
+ };
638
+
639
+ //#endregion
640
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/pg-core/columns/enum.js
641
+ var PgEnumObjectColumnBuilder = class extends PgColumnBuilder {
642
+ static [entityKind] = "PgEnumObjectColumnBuilder";
643
+ constructor(name, enumInstance) {
644
+ super(name, "string", "PgEnumObjectColumn");
645
+ this.config.enum = enumInstance;
646
+ }
647
+ /** @internal */
648
+ build(table) {
649
+ return new PgEnumObjectColumn(table, this.config);
650
+ }
651
+ };
652
+ var PgEnumObjectColumn = class extends PgColumn {
653
+ static [entityKind] = "PgEnumObjectColumn";
654
+ enum;
655
+ enumValues = this.config.enum.enumValues;
656
+ constructor(table, config) {
657
+ super(table, config);
658
+ this.enum = config.enum;
659
+ }
660
+ getSQLType() {
661
+ return this.enum.enumName;
662
+ }
663
+ };
664
+ const isPgEnumSym = Symbol.for("drizzle:isPgEnum");
665
+ function isPgEnum(obj) {
666
+ return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
667
+ }
668
+ var PgEnumColumnBuilder = class extends PgColumnBuilder {
669
+ static [entityKind] = "PgEnumColumnBuilder";
670
+ constructor(name, enumInstance) {
671
+ super(name, "string", "PgEnumColumn");
672
+ this.config.enum = enumInstance;
673
+ }
674
+ /** @internal */
675
+ build(table) {
676
+ return new PgEnumColumn(table, this.config);
677
+ }
678
+ };
679
+ var PgEnumColumn = class extends PgColumn {
680
+ static [entityKind] = "PgEnumColumn";
681
+ enum = this.config.enum;
682
+ enumValues = this.config.enum.enumValues;
683
+ constructor(table, config) {
684
+ super(table, config);
685
+ this.enum = config.enum;
686
+ }
687
+ getSQLType() {
688
+ return this.enum.enumName;
689
+ }
690
+ };
691
+
692
+ //#endregion
693
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/subquery.js
694
+ var Subquery = class {
695
+ static [entityKind] = "Subquery";
696
+ constructor(sql$1, fields, alias, isWith = false, usedTables = []) {
697
+ this._ = {
698
+ brand: "Subquery",
699
+ sql: sql$1,
700
+ selectedFields: fields,
701
+ alias,
702
+ isWith,
703
+ usedTables
704
+ };
705
+ }
706
+ };
707
+ var WithSubquery = class extends Subquery {
708
+ static [entityKind] = "WithSubquery";
709
+ };
710
+
711
+ //#endregion
712
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/tracing.js
713
+ const tracer = { startActiveSpan(name, fn) {
714
+ return fn();
715
+ } };
716
+
717
+ //#endregion
718
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/view-common.js
719
+ const ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
720
+
721
+ //#endregion
722
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sql/sql.js
723
+ var FakePrimitiveParam = class {
724
+ static [entityKind] = "FakePrimitiveParam";
725
+ };
726
+ function isSQLWrapper(value) {
727
+ return value !== null && value !== void 0 && typeof value.getSQL === "function";
728
+ }
729
+ function mergeQueries(queries) {
730
+ const result = {
731
+ sql: "",
732
+ params: []
733
+ };
734
+ for (const query of queries) {
735
+ result.sql += query.sql;
736
+ result.params.push(...query.params);
737
+ if (query.typings?.length) {
738
+ if (!result.typings) result.typings = [];
739
+ result.typings.push(...query.typings);
740
+ }
741
+ }
742
+ return result;
743
+ }
744
+ var StringChunk = class {
745
+ static [entityKind] = "StringChunk";
746
+ value;
747
+ constructor(value) {
748
+ this.value = Array.isArray(value) ? value : [value];
749
+ }
750
+ getSQL() {
751
+ return new SQL([this]);
752
+ }
753
+ };
754
+ var SQL = class SQL {
755
+ constructor(queryChunks) {
756
+ this.queryChunks = queryChunks;
757
+ for (const chunk of queryChunks) if (is(chunk, Table)) {
758
+ const schemaName = chunk[Table.Symbol.Schema];
759
+ this.usedTables.push(schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]);
760
+ }
761
+ }
762
+ static [entityKind] = "SQL";
763
+ /** @internal */
764
+ decoder = noopDecoder;
765
+ shouldInlineParams = false;
766
+ /** @internal */
767
+ usedTables = [];
768
+ append(query) {
769
+ this.queryChunks.push(...query.queryChunks);
770
+ return this;
771
+ }
772
+ toQuery(config) {
773
+ return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
774
+ const query = this.buildQueryFromSourceParams(this.queryChunks, config);
775
+ span?.setAttributes({
776
+ "drizzle.query.text": query.sql,
777
+ "drizzle.query.params": JSON.stringify(query.params)
778
+ });
779
+ return query;
780
+ });
781
+ }
782
+ buildQueryFromSourceParams(chunks, _config) {
783
+ const config = Object.assign({}, _config, {
784
+ inlineParams: _config.inlineParams || this.shouldInlineParams,
785
+ paramStartIndex: _config.paramStartIndex || { value: 0 }
786
+ });
787
+ const { casing, escapeName, escapeParam, prepareTyping, inlineParams, paramStartIndex } = config;
788
+ return mergeQueries(chunks.map((chunk) => {
789
+ if (is(chunk, StringChunk)) return {
790
+ sql: chunk.value.join(""),
791
+ params: []
792
+ };
793
+ if (is(chunk, Name)) return {
794
+ sql: escapeName(chunk.value),
795
+ params: []
796
+ };
797
+ if (chunk === void 0) return {
798
+ sql: "",
799
+ params: []
800
+ };
801
+ if (Array.isArray(chunk)) {
802
+ const result = [new StringChunk("(")];
803
+ for (const [i, p] of chunk.entries()) {
804
+ result.push(p);
805
+ if (i < chunk.length - 1) result.push(new StringChunk(", "));
806
+ }
807
+ result.push(new StringChunk(")"));
808
+ return this.buildQueryFromSourceParams(result, config);
809
+ }
810
+ if (is(chunk, SQL)) return this.buildQueryFromSourceParams(chunk.queryChunks, {
811
+ ...config,
812
+ inlineParams: inlineParams || chunk.shouldInlineParams
813
+ });
814
+ if (is(chunk, Table)) {
815
+ const schemaName = chunk[Table.Symbol.Schema];
816
+ const tableName = chunk[Table.Symbol.Name];
817
+ return {
818
+ sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
819
+ params: []
820
+ };
821
+ }
822
+ if (is(chunk, Column)) {
823
+ const columnName = casing.getColumnCasing(chunk);
824
+ if (_config.invokeSource === "indexes") return {
825
+ sql: escapeName(columnName),
826
+ params: []
827
+ };
828
+ const schemaName = chunk.table[Table.Symbol.Schema];
829
+ return {
830
+ sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
831
+ params: []
832
+ };
833
+ }
834
+ if (is(chunk, View)) {
835
+ const schemaName = chunk[ViewBaseConfig].schema;
836
+ const viewName = chunk[ViewBaseConfig].name;
837
+ return {
838
+ sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
839
+ params: []
840
+ };
841
+ }
842
+ if (is(chunk, Param)) {
843
+ if (is(chunk.value, Placeholder)) return {
844
+ sql: escapeParam(paramStartIndex.value++, chunk),
845
+ params: [chunk],
846
+ typings: ["none"]
847
+ };
848
+ const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
849
+ if (is(mappedValue, SQL)) return this.buildQueryFromSourceParams([mappedValue], config);
850
+ if (inlineParams) return {
851
+ sql: this.mapInlineParam(mappedValue, config),
852
+ params: []
853
+ };
854
+ let typings = ["none"];
855
+ if (prepareTyping) typings = [prepareTyping(chunk.encoder)];
856
+ return {
857
+ sql: escapeParam(paramStartIndex.value++, mappedValue),
858
+ params: [mappedValue],
859
+ typings
860
+ };
861
+ }
862
+ if (is(chunk, Placeholder)) return {
863
+ sql: escapeParam(paramStartIndex.value++, chunk),
864
+ params: [chunk],
865
+ typings: ["none"]
866
+ };
867
+ if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== void 0) return {
868
+ sql: escapeName(chunk.fieldAlias),
869
+ params: []
870
+ };
871
+ if (is(chunk, Subquery)) {
872
+ if (chunk._.isWith) return {
873
+ sql: escapeName(chunk._.alias),
874
+ params: []
875
+ };
876
+ return this.buildQueryFromSourceParams([
877
+ new StringChunk("("),
878
+ chunk._.sql,
879
+ new StringChunk(") "),
880
+ new Name(chunk._.alias)
881
+ ], config);
882
+ }
883
+ if (isPgEnum(chunk)) {
884
+ if (chunk.schema) return {
885
+ sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName),
886
+ params: []
887
+ };
888
+ return {
889
+ sql: escapeName(chunk.enumName),
890
+ params: []
891
+ };
892
+ }
893
+ if (isSQLWrapper(chunk)) {
894
+ if (chunk.shouldOmitSQLParens?.()) return this.buildQueryFromSourceParams([chunk.getSQL()], config);
895
+ return this.buildQueryFromSourceParams([
896
+ new StringChunk("("),
897
+ chunk.getSQL(),
898
+ new StringChunk(")")
899
+ ], config);
900
+ }
901
+ if (inlineParams) return {
902
+ sql: this.mapInlineParam(chunk, config),
903
+ params: []
904
+ };
905
+ return {
906
+ sql: escapeParam(paramStartIndex.value++, chunk),
907
+ params: [chunk],
908
+ typings: ["none"]
909
+ };
910
+ }));
911
+ }
912
+ mapInlineParam(chunk, { escapeString }) {
913
+ if (chunk === null) return "null";
914
+ if (typeof chunk === "number" || typeof chunk === "boolean") return chunk.toString();
915
+ if (typeof chunk === "string") return escapeString(chunk);
916
+ if (typeof chunk === "object") {
917
+ const mappedValueAsString = chunk.toString();
918
+ if (mappedValueAsString === "[object Object]") return escapeString(JSON.stringify(chunk));
919
+ return escapeString(mappedValueAsString);
920
+ }
921
+ throw new Error("Unexpected param value: " + chunk);
922
+ }
923
+ getSQL() {
924
+ return this;
925
+ }
926
+ as(alias) {
927
+ if (alias === void 0) return this;
928
+ return new SQL.Aliased(this, alias);
929
+ }
930
+ mapWith(decoder) {
931
+ this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
932
+ return this;
933
+ }
934
+ inlineParams() {
935
+ this.shouldInlineParams = true;
936
+ return this;
937
+ }
938
+ /**
939
+ * This method is used to conditionally include a part of the query.
940
+ *
941
+ * @param condition - Condition to check
942
+ * @returns itself if the condition is `true`, otherwise `undefined`
943
+ */
944
+ if(condition) {
945
+ return condition ? this : void 0;
946
+ }
947
+ };
948
+ var Name = class {
949
+ constructor(value) {
950
+ this.value = value;
951
+ }
952
+ static [entityKind] = "Name";
953
+ brand;
954
+ getSQL() {
955
+ return new SQL([this]);
956
+ }
957
+ };
958
+ function isDriverValueEncoder(value) {
959
+ return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
960
+ }
961
+ const noopDecoder = { mapFromDriverValue: (value) => value };
962
+ const noopEncoder = { mapToDriverValue: (value) => value };
963
+ const noopMapper = {
964
+ ...noopDecoder,
965
+ ...noopEncoder
966
+ };
967
+ var Param = class {
968
+ /**
969
+ * @param value - Parameter value
970
+ * @param encoder - Encoder to convert the value to a driver parameter
971
+ */
972
+ constructor(value, encoder = noopEncoder) {
973
+ this.value = value;
974
+ this.encoder = encoder;
975
+ }
976
+ static [entityKind] = "Param";
977
+ brand;
978
+ getSQL() {
979
+ return new SQL([this]);
980
+ }
981
+ };
982
+ function sql(strings, ...params) {
983
+ const queryChunks = [];
984
+ if (params.length > 0 || strings.length > 0 && strings[0] !== "") queryChunks.push(new StringChunk(strings[0]));
985
+ for (const [paramIndex, param2] of params.entries()) queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
986
+ return new SQL(queryChunks);
987
+ }
988
+ ((sql2) => {
989
+ function empty() {
990
+ return new SQL([]);
991
+ }
992
+ sql2.empty = empty;
993
+ function fromList(list) {
994
+ return new SQL(list);
995
+ }
996
+ sql2.fromList = fromList;
997
+ function raw(str) {
998
+ return new SQL([new StringChunk(str)]);
999
+ }
1000
+ sql2.raw = raw;
1001
+ function join(chunks, separator) {
1002
+ const result = [];
1003
+ for (const [i, chunk] of chunks.entries()) {
1004
+ if (i > 0 && separator !== void 0) result.push(separator);
1005
+ result.push(chunk);
1006
+ }
1007
+ return new SQL(result);
1008
+ }
1009
+ sql2.join = join;
1010
+ function identifier(value) {
1011
+ return new Name(value);
1012
+ }
1013
+ sql2.identifier = identifier;
1014
+ function placeholder2(name2) {
1015
+ return new Placeholder(name2);
1016
+ }
1017
+ sql2.placeholder = placeholder2;
1018
+ function param2(value, encoder) {
1019
+ return new Param(value, encoder);
1020
+ }
1021
+ sql2.param = param2;
1022
+ })(sql || (sql = {}));
1023
+ ((SQL2) => {
1024
+ class Aliased {
1025
+ constructor(sql2, fieldAlias) {
1026
+ this.sql = sql2;
1027
+ this.fieldAlias = fieldAlias;
1028
+ }
1029
+ static [entityKind] = "SQL.Aliased";
1030
+ /** @internal */
1031
+ isSelectionField = false;
1032
+ getSQL() {
1033
+ return this.sql;
1034
+ }
1035
+ /** @internal */
1036
+ clone() {
1037
+ return new Aliased(this.sql, this.fieldAlias);
1038
+ }
1039
+ }
1040
+ SQL2.Aliased = Aliased;
1041
+ })(SQL || (SQL = {}));
1042
+ var Placeholder = class {
1043
+ constructor(name2) {
1044
+ this.name = name2;
1045
+ }
1046
+ static [entityKind] = "Placeholder";
1047
+ getSQL() {
1048
+ return new SQL([this]);
1049
+ }
1050
+ };
1051
+ function fillPlaceholders(params, values) {
1052
+ return params.map((p) => {
1053
+ if (is(p, Placeholder)) {
1054
+ if (!(p.name in values)) throw new Error(`No value for placeholder "${p.name}" was provided`);
1055
+ return values[p.name];
1056
+ }
1057
+ if (is(p, Param) && is(p.value, Placeholder)) {
1058
+ if (!(p.value.name in values)) throw new Error(`No value for placeholder "${p.value.name}" was provided`);
1059
+ return p.encoder.mapToDriverValue(values[p.value.name]);
1060
+ }
1061
+ return p;
1062
+ });
1063
+ }
1064
+ const IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
1065
+ var View = class {
1066
+ static [entityKind] = "View";
1067
+ /** @internal */
1068
+ [ViewBaseConfig];
1069
+ /** @internal */
1070
+ [IsDrizzleView] = true;
1071
+ constructor({ name: name2, schema, selectedFields, query }) {
1072
+ this[ViewBaseConfig] = {
1073
+ name: name2,
1074
+ originalName: name2,
1075
+ schema,
1076
+ selectedFields,
1077
+ query,
1078
+ isExisting: !query,
1079
+ isAlias: false
1080
+ };
1081
+ }
1082
+ getSQL() {
1083
+ return new SQL([this]);
1084
+ }
1085
+ };
1086
+ Column.prototype.getSQL = function() {
1087
+ return new SQL([this]);
1088
+ };
1089
+ Table.prototype.getSQL = function() {
1090
+ return new SQL([this]);
1091
+ };
1092
+ Subquery.prototype.getSQL = function() {
1093
+ return new SQL([this]);
1094
+ };
1095
+
1096
+ //#endregion
1097
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/utils.js
1098
+ function mapResultRow(columns$1, row, joinsNotNullableMap) {
1099
+ const nullifyMap = {};
1100
+ const result = columns$1.reduce((result2, { path, field }, columnIndex) => {
1101
+ let decoder;
1102
+ if (is(field, Column)) decoder = field;
1103
+ else if (is(field, SQL)) decoder = field.decoder;
1104
+ else decoder = field.sql.decoder;
1105
+ let node = result2;
1106
+ for (const [pathChunkIndex, pathChunk] of path.entries()) if (pathChunkIndex < path.length - 1) {
1107
+ if (!(pathChunk in node)) node[pathChunk] = {};
1108
+ node = node[pathChunk];
1109
+ } else {
1110
+ const rawValue = row[columnIndex];
1111
+ const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
1112
+ if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
1113
+ const objectName = path[0];
1114
+ if (!(objectName in nullifyMap)) nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
1115
+ else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) nullifyMap[objectName] = false;
1116
+ }
1117
+ }
1118
+ return result2;
1119
+ }, {});
1120
+ if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
1121
+ for (const [objectName, tableName] of Object.entries(nullifyMap)) if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) result[objectName] = null;
1122
+ }
1123
+ return result;
1124
+ }
1125
+ function orderSelectedFields(fields, pathPrefix) {
1126
+ return Object.entries(fields).reduce((result, [name, field]) => {
1127
+ if (typeof name !== "string") return result;
1128
+ const newPath = pathPrefix ? [...pathPrefix, name] : [name];
1129
+ if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) result.push({
1130
+ path: newPath,
1131
+ field
1132
+ });
1133
+ else if (is(field, Table)) result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
1134
+ else result.push(...orderSelectedFields(field, newPath));
1135
+ return result;
1136
+ }, []);
1137
+ }
1138
+ function haveSameKeys(left, right) {
1139
+ const leftKeys = Object.keys(left);
1140
+ const rightKeys = Object.keys(right);
1141
+ if (leftKeys.length !== rightKeys.length) return false;
1142
+ for (const [index, key] of leftKeys.entries()) if (key !== rightKeys[index]) return false;
1143
+ return true;
1144
+ }
1145
+ function mapUpdateSet(table, values) {
1146
+ const entries$1 = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {
1147
+ if (is(value, SQL) || is(value, Column)) return [key, value];
1148
+ else return [key, new Param(value, table[Table.Symbol.Columns][key])];
1149
+ });
1150
+ if (entries$1.length === 0) throw new Error("No values to set");
1151
+ return Object.fromEntries(entries$1);
1152
+ }
1153
+ function applyMixins(baseClass, extendedClasses) {
1154
+ for (const extendedClass of extendedClasses) for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
1155
+ if (name === "constructor") continue;
1156
+ Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null));
1157
+ }
1158
+ }
1159
+ function getTableColumns(table) {
1160
+ return table[Table.Symbol.Columns];
1161
+ }
1162
+ function getTableLikeName(table) {
1163
+ return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];
1164
+ }
1165
+ function getColumnNameAndConfig(a, b) {
1166
+ return {
1167
+ name: typeof a === "string" && a.length > 0 ? a : "",
1168
+ config: typeof a === "object" ? a : b
1169
+ };
1170
+ }
1171
+ const textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder();
1172
+
1173
+ //#endregion
1174
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/pg-core/table.js
1175
+ const InlineForeignKeys$1 = Symbol.for("drizzle:PgInlineForeignKeys");
1176
+ const EnableRLS = Symbol.for("drizzle:EnableRLS");
1177
+ var PgTable = class extends Table {
1178
+ static [entityKind] = "PgTable";
1179
+ /** @internal */
1180
+ static Symbol = Object.assign({}, Table.Symbol, {
1181
+ InlineForeignKeys: InlineForeignKeys$1,
1182
+ EnableRLS
1183
+ });
1184
+ /**@internal */
1185
+ [InlineForeignKeys$1] = [];
1186
+ /** @internal */
1187
+ [EnableRLS] = false;
1188
+ /** @internal */
1189
+ [Table.Symbol.ExtraConfigBuilder] = void 0;
1190
+ /** @internal */
1191
+ [Table.Symbol.ExtraConfigColumns] = {};
1192
+ };
1193
+
1194
+ //#endregion
1195
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/pg-core/primary-keys.js
1196
+ var PrimaryKeyBuilder$1 = class {
1197
+ static [entityKind] = "PgPrimaryKeyBuilder";
1198
+ /** @internal */
1199
+ columns;
1200
+ /** @internal */
1201
+ name;
1202
+ constructor(columns$1, name) {
1203
+ this.columns = columns$1;
1204
+ this.name = name;
1205
+ }
1206
+ /** @internal */
1207
+ build(table) {
1208
+ return new PrimaryKey$1(table, this.columns, this.name);
1209
+ }
1210
+ };
1211
+ var PrimaryKey$1 = class {
1212
+ constructor(table, columns$1, name) {
1213
+ this.table = table;
1214
+ this.columns = columns$1;
1215
+ this.name = name;
1216
+ }
1217
+ static [entityKind] = "PgPrimaryKey";
1218
+ columns;
1219
+ name;
1220
+ getName() {
1221
+ return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
1222
+ }
1223
+ };
1224
+
1225
+ //#endregion
1226
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sql/expressions/conditions.js
1227
+ function bindIfParam(value, column) {
1228
+ if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) return new Param(value, column);
1229
+ return value;
1230
+ }
1231
+ const eq = (left, right) => {
1232
+ return sql`${left} = ${bindIfParam(right, left)}`;
1233
+ };
1234
+ const ne = (left, right) => {
1235
+ return sql`${left} <> ${bindIfParam(right, left)}`;
1236
+ };
1237
+ function and(...unfilteredConditions) {
1238
+ const conditions = unfilteredConditions.filter((c) => c !== void 0);
1239
+ if (conditions.length === 0) return;
1240
+ if (conditions.length === 1) return new SQL(conditions);
1241
+ return new SQL([
1242
+ new StringChunk("("),
1243
+ sql.join(conditions, new StringChunk(" and ")),
1244
+ new StringChunk(")")
1245
+ ]);
1246
+ }
1247
+ function or(...unfilteredConditions) {
1248
+ const conditions = unfilteredConditions.filter((c) => c !== void 0);
1249
+ if (conditions.length === 0) return;
1250
+ if (conditions.length === 1) return new SQL(conditions);
1251
+ return new SQL([
1252
+ new StringChunk("("),
1253
+ sql.join(conditions, new StringChunk(" or ")),
1254
+ new StringChunk(")")
1255
+ ]);
1256
+ }
1257
+ function not(condition) {
1258
+ return sql`not ${condition}`;
1259
+ }
1260
+ const gt = (left, right) => {
1261
+ return sql`${left} > ${bindIfParam(right, left)}`;
1262
+ };
1263
+ const gte = (left, right) => {
1264
+ return sql`${left} >= ${bindIfParam(right, left)}`;
1265
+ };
1266
+ const lt = (left, right) => {
1267
+ return sql`${left} < ${bindIfParam(right, left)}`;
1268
+ };
1269
+ const lte = (left, right) => {
1270
+ return sql`${left} <= ${bindIfParam(right, left)}`;
1271
+ };
1272
+ function inArray(column, values) {
1273
+ if (Array.isArray(values)) {
1274
+ if (values.length === 0) return sql`false`;
1275
+ return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
1276
+ }
1277
+ return sql`${column} in ${bindIfParam(values, column)}`;
1278
+ }
1279
+ function notInArray(column, values) {
1280
+ if (Array.isArray(values)) {
1281
+ if (values.length === 0) return sql`true`;
1282
+ return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
1283
+ }
1284
+ return sql`${column} not in ${bindIfParam(values, column)}`;
1285
+ }
1286
+ function isNull(value) {
1287
+ return sql`${value} is null`;
1288
+ }
1289
+ function isNotNull(value) {
1290
+ return sql`${value} is not null`;
1291
+ }
1292
+ function exists(subquery) {
1293
+ return sql`exists ${subquery}`;
1294
+ }
1295
+ function notExists(subquery) {
1296
+ return sql`not exists ${subquery}`;
1297
+ }
1298
+ function between(column, min, max) {
1299
+ return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1300
+ }
1301
+ function notBetween(column, min, max) {
1302
+ return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1303
+ }
1304
+ function like(column, value) {
1305
+ return sql`${column} like ${value}`;
1306
+ }
1307
+ function notLike(column, value) {
1308
+ return sql`${column} not like ${value}`;
1309
+ }
1310
+ function ilike(column, value) {
1311
+ return sql`${column} ilike ${value}`;
1312
+ }
1313
+ function notIlike(column, value) {
1314
+ return sql`${column} not ilike ${value}`;
1315
+ }
1316
+
1317
+ //#endregion
1318
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sql/expressions/select.js
1319
+ function asc(column) {
1320
+ return sql`${column} asc`;
1321
+ }
1322
+ function desc(column) {
1323
+ return sql`${column} desc`;
1324
+ }
1325
+
1326
+ //#endregion
1327
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/relations.js
1328
+ var Relation = class {
1329
+ constructor(sourceTable, referencedTable, relationName) {
1330
+ this.sourceTable = sourceTable;
1331
+ this.referencedTable = referencedTable;
1332
+ this.relationName = relationName;
1333
+ this.referencedTableName = referencedTable[Table.Symbol.Name];
1334
+ }
1335
+ static [entityKind] = "Relation";
1336
+ referencedTableName;
1337
+ fieldName;
1338
+ };
1339
+ var Relations = class {
1340
+ constructor(table, config) {
1341
+ this.table = table;
1342
+ this.config = config;
1343
+ }
1344
+ static [entityKind] = "Relations";
1345
+ };
1346
+ var One = class One extends Relation {
1347
+ constructor(sourceTable, referencedTable, config, isNullable) {
1348
+ super(sourceTable, referencedTable, config?.relationName);
1349
+ this.config = config;
1350
+ this.isNullable = isNullable;
1351
+ }
1352
+ static [entityKind] = "One";
1353
+ withFieldName(fieldName) {
1354
+ const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable);
1355
+ relation.fieldName = fieldName;
1356
+ return relation;
1357
+ }
1358
+ };
1359
+ var Many = class Many extends Relation {
1360
+ constructor(sourceTable, referencedTable, config) {
1361
+ super(sourceTable, referencedTable, config?.relationName);
1362
+ this.config = config;
1363
+ }
1364
+ static [entityKind] = "Many";
1365
+ withFieldName(fieldName) {
1366
+ const relation = new Many(this.sourceTable, this.referencedTable, this.config);
1367
+ relation.fieldName = fieldName;
1368
+ return relation;
1369
+ }
1370
+ };
1371
+ function getOperators() {
1372
+ return {
1373
+ and,
1374
+ between,
1375
+ eq,
1376
+ exists,
1377
+ gt,
1378
+ gte,
1379
+ ilike,
1380
+ inArray,
1381
+ isNull,
1382
+ isNotNull,
1383
+ like,
1384
+ lt,
1385
+ lte,
1386
+ ne,
1387
+ not,
1388
+ notBetween,
1389
+ notExists,
1390
+ notLike,
1391
+ notIlike,
1392
+ notInArray,
1393
+ or,
1394
+ sql
1395
+ };
1396
+ }
1397
+ function getOrderByOperators() {
1398
+ return {
1399
+ sql,
1400
+ asc,
1401
+ desc
1402
+ };
1403
+ }
1404
+ function extractTablesRelationalConfig(schema, configHelpers) {
1405
+ if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) schema = schema["default"];
1406
+ const tableNamesMap = {};
1407
+ const relationsBuffer = {};
1408
+ const tablesConfig = {};
1409
+ for (const [key, value] of Object.entries(schema)) if (is(value, Table)) {
1410
+ const dbName = getTableUniqueName(value);
1411
+ const bufferedRelations = relationsBuffer[dbName];
1412
+ tableNamesMap[dbName] = key;
1413
+ tablesConfig[key] = {
1414
+ tsName: key,
1415
+ dbName: value[Table.Symbol.Name],
1416
+ schema: value[Table.Symbol.Schema],
1417
+ columns: value[Table.Symbol.Columns],
1418
+ relations: bufferedRelations?.relations ?? {},
1419
+ primaryKey: bufferedRelations?.primaryKey ?? []
1420
+ };
1421
+ for (const column of Object.values(value[Table.Symbol.Columns])) if (column.primary) tablesConfig[key].primaryKey.push(column);
1422
+ const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
1423
+ if (extraConfig) {
1424
+ for (const configEntry of Object.values(extraConfig)) if (is(configEntry, PrimaryKeyBuilder$1)) tablesConfig[key].primaryKey.push(...configEntry.columns);
1425
+ }
1426
+ } else if (is(value, Relations)) {
1427
+ const dbName = getTableUniqueName(value.table);
1428
+ const tableName = tableNamesMap[dbName];
1429
+ const relations2 = value.config(configHelpers(value.table));
1430
+ let primaryKey$1;
1431
+ for (const [relationName, relation] of Object.entries(relations2)) if (tableName) {
1432
+ const tableConfig = tablesConfig[tableName];
1433
+ tableConfig.relations[relationName] = relation;
1434
+ } else {
1435
+ if (!(dbName in relationsBuffer)) relationsBuffer[dbName] = {
1436
+ relations: {},
1437
+ primaryKey: primaryKey$1
1438
+ };
1439
+ relationsBuffer[dbName].relations[relationName] = relation;
1440
+ }
1441
+ }
1442
+ return {
1443
+ tables: tablesConfig,
1444
+ tableNamesMap
1445
+ };
1446
+ }
1447
+ function createOne(sourceTable) {
1448
+ return function one(table, config) {
1449
+ return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false);
1450
+ };
1451
+ }
1452
+ function createMany(sourceTable) {
1453
+ return function many(referencedTable, config) {
1454
+ return new Many(sourceTable, referencedTable, config);
1455
+ };
1456
+ }
1457
+ function normalizeRelation(schema, tableNamesMap, relation) {
1458
+ if (is(relation, One) && relation.config) return {
1459
+ fields: relation.config.fields,
1460
+ references: relation.config.references
1461
+ };
1462
+ const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
1463
+ if (!referencedTableTsName) throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`);
1464
+ const referencedTableConfig = schema[referencedTableTsName];
1465
+ if (!referencedTableConfig) throw new Error(`Table "${referencedTableTsName}" not found in schema`);
1466
+ const sourceTable = relation.sourceTable;
1467
+ const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
1468
+ if (!sourceTableTsName) throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`);
1469
+ const reverseRelations = [];
1470
+ for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) reverseRelations.push(referencedTableRelation);
1471
+ if (reverseRelations.length > 1) throw relation.relationName ? /* @__PURE__ */ new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : /* @__PURE__ */ new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
1472
+ if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) return {
1473
+ fields: reverseRelations[0].config.references,
1474
+ references: reverseRelations[0].config.fields
1475
+ };
1476
+ throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`);
1477
+ }
1478
+ function createTableRelationsHelpers(sourceTable) {
1479
+ return {
1480
+ one: createOne(sourceTable),
1481
+ many: createMany(sourceTable)
1482
+ };
1483
+ }
1484
+ function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
1485
+ const result = {};
1486
+ for (const [selectionItemIndex, selectionItem] of buildQueryResultSelection.entries()) if (selectionItem.isJson) {
1487
+ const relation = tableConfig.relations[selectionItem.tsKey];
1488
+ const rawSubRows = row[selectionItemIndex];
1489
+ const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
1490
+ result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue));
1491
+ } else {
1492
+ const value = mapColumnValue(row[selectionItemIndex]);
1493
+ const field = selectionItem.field;
1494
+ let decoder;
1495
+ if (is(field, Column)) decoder = field;
1496
+ else if (is(field, SQL)) decoder = field.decoder;
1497
+ else decoder = field.sql.decoder;
1498
+ result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
1499
+ }
1500
+ return result;
1501
+ }
1502
+
1503
+ //#endregion
1504
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/alias.js
1505
+ var ColumnAliasProxyHandler = class {
1506
+ constructor(table) {
1507
+ this.table = table;
1508
+ }
1509
+ static [entityKind] = "ColumnAliasProxyHandler";
1510
+ get(columnObj, prop) {
1511
+ if (prop === "table") return this.table;
1512
+ return columnObj[prop];
1513
+ }
1514
+ };
1515
+ var TableAliasProxyHandler = class {
1516
+ constructor(alias, replaceOriginalName) {
1517
+ this.alias = alias;
1518
+ this.replaceOriginalName = replaceOriginalName;
1519
+ }
1520
+ static [entityKind] = "TableAliasProxyHandler";
1521
+ get(target, prop) {
1522
+ if (prop === Table.Symbol.IsAlias) return true;
1523
+ if (prop === Table.Symbol.Name) return this.alias;
1524
+ if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) return this.alias;
1525
+ if (prop === ViewBaseConfig) return {
1526
+ ...target[ViewBaseConfig],
1527
+ name: this.alias,
1528
+ isAlias: true
1529
+ };
1530
+ if (prop === Table.Symbol.Columns) {
1531
+ const columns$1 = target[Table.Symbol.Columns];
1532
+ if (!columns$1) return columns$1;
1533
+ const proxiedColumns = {};
1534
+ Object.keys(columns$1).map((key) => {
1535
+ proxiedColumns[key] = new Proxy(columns$1[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
1536
+ });
1537
+ return proxiedColumns;
1538
+ }
1539
+ const value = target[prop];
1540
+ if (is(value, Column)) return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
1541
+ return value;
1542
+ }
1543
+ };
1544
+ var RelationTableAliasProxyHandler = class {
1545
+ constructor(alias) {
1546
+ this.alias = alias;
1547
+ }
1548
+ static [entityKind] = "RelationTableAliasProxyHandler";
1549
+ get(target, prop) {
1550
+ if (prop === "sourceTable") return aliasedTable(target.sourceTable, this.alias);
1551
+ return target[prop];
1552
+ }
1553
+ };
1554
+ function aliasedTable(table, tableAlias) {
1555
+ return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
1556
+ }
1557
+ function aliasedTableColumn(column, tableAlias) {
1558
+ return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
1559
+ }
1560
+ function mapColumnsInAliasedSQLToAlias(query, alias) {
1561
+ return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
1562
+ }
1563
+ function mapColumnsInSQLToAlias(query, alias) {
1564
+ return sql.join(query.queryChunks.map((c) => {
1565
+ if (is(c, Column)) return aliasedTableColumn(c, alias);
1566
+ if (is(c, SQL)) return mapColumnsInSQLToAlias(c, alias);
1567
+ if (is(c, SQL.Aliased)) return mapColumnsInAliasedSQLToAlias(c, alias);
1568
+ return c;
1569
+ }));
1570
+ }
1571
+
1572
+ //#endregion
1573
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/selection-proxy.js
1574
+ var SelectionProxyHandler = class SelectionProxyHandler {
1575
+ static [entityKind] = "SelectionProxyHandler";
1576
+ config;
1577
+ constructor(config) {
1578
+ this.config = { ...config };
1579
+ }
1580
+ get(subquery, prop) {
1581
+ if (prop === "_") return {
1582
+ ...subquery["_"],
1583
+ selectedFields: new Proxy(subquery._.selectedFields, this)
1584
+ };
1585
+ if (prop === ViewBaseConfig) return {
1586
+ ...subquery[ViewBaseConfig],
1587
+ selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
1588
+ };
1589
+ if (typeof prop === "symbol") return subquery[prop];
1590
+ const value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];
1591
+ if (is(value, SQL.Aliased)) {
1592
+ if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) return value.sql;
1593
+ const newValue = value.clone();
1594
+ newValue.isSelectionField = true;
1595
+ return newValue;
1596
+ }
1597
+ if (is(value, SQL)) {
1598
+ if (this.config.sqlBehavior === "sql") return value;
1599
+ throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
1600
+ }
1601
+ if (is(value, Column)) {
1602
+ if (this.config.alias) return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
1603
+ return value;
1604
+ }
1605
+ if (typeof value !== "object" || value === null) return value;
1606
+ return new Proxy(value, new SelectionProxyHandler(this.config));
1607
+ }
1608
+ };
1609
+
1610
+ //#endregion
1611
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/query-promise.js
1612
+ var QueryPromise = class {
1613
+ static [entityKind] = "QueryPromise";
1614
+ [Symbol.toStringTag] = "QueryPromise";
1615
+ catch(onRejected) {
1616
+ return this.then(void 0, onRejected);
1617
+ }
1618
+ finally(onFinally) {
1619
+ return this.then((value) => {
1620
+ onFinally?.();
1621
+ return value;
1622
+ }, (reason) => {
1623
+ onFinally?.();
1624
+ throw reason;
1625
+ });
1626
+ }
1627
+ then(onFulfilled, onRejected) {
1628
+ return this.execute().then(onFulfilled, onRejected);
1629
+ }
1630
+ };
1631
+
1632
+ //#endregion
1633
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
1634
+ var ForeignKeyBuilder = class {
1635
+ static [entityKind] = "SQLiteForeignKeyBuilder";
1636
+ /** @internal */
1637
+ reference;
1638
+ /** @internal */
1639
+ _onUpdate;
1640
+ /** @internal */
1641
+ _onDelete;
1642
+ constructor(config, actions) {
1643
+ this.reference = () => {
1644
+ const { name, columns: columns$1, foreignColumns } = config();
1645
+ return {
1646
+ name,
1647
+ columns: columns$1,
1648
+ foreignTable: foreignColumns[0].table,
1649
+ foreignColumns
1650
+ };
1651
+ };
1652
+ if (actions) {
1653
+ this._onUpdate = actions.onUpdate;
1654
+ this._onDelete = actions.onDelete;
1655
+ }
1656
+ }
1657
+ onUpdate(action) {
1658
+ this._onUpdate = action;
1659
+ return this;
1660
+ }
1661
+ onDelete(action) {
1662
+ this._onDelete = action;
1663
+ return this;
1664
+ }
1665
+ /** @internal */
1666
+ build(table) {
1667
+ return new ForeignKey(table, this);
1668
+ }
1669
+ };
1670
+ var ForeignKey = class {
1671
+ constructor(table, builder) {
1672
+ this.table = table;
1673
+ this.reference = builder.reference;
1674
+ this.onUpdate = builder._onUpdate;
1675
+ this.onDelete = builder._onDelete;
1676
+ }
1677
+ static [entityKind] = "SQLiteForeignKey";
1678
+ reference;
1679
+ onUpdate;
1680
+ onDelete;
1681
+ getName() {
1682
+ const { name, columns: columns$1, foreignColumns } = this.reference();
1683
+ const columnNames = columns$1.map((column) => column.name);
1684
+ const foreignColumnNames = foreignColumns.map((column) => column.name);
1685
+ const chunks = [
1686
+ this.table[TableName],
1687
+ ...columnNames,
1688
+ foreignColumns[0].table[TableName],
1689
+ ...foreignColumnNames
1690
+ ];
1691
+ return name ?? `${chunks.join("_")}_fk`;
1692
+ }
1693
+ };
1694
+
1695
+ //#endregion
1696
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
1697
+ function uniqueKeyName(table, columns$1) {
1698
+ return `${table[TableName]}_${columns$1.join("_")}_unique`;
1699
+ }
1700
+ var UniqueConstraintBuilder = class {
1701
+ constructor(columns$1, name) {
1702
+ this.name = name;
1703
+ this.columns = columns$1;
1704
+ }
1705
+ static [entityKind] = "SQLiteUniqueConstraintBuilder";
1706
+ /** @internal */
1707
+ columns;
1708
+ /** @internal */
1709
+ build(table) {
1710
+ return new UniqueConstraint(table, this.columns, this.name);
1711
+ }
1712
+ };
1713
+ var UniqueOnConstraintBuilder = class {
1714
+ static [entityKind] = "SQLiteUniqueOnConstraintBuilder";
1715
+ /** @internal */
1716
+ name;
1717
+ constructor(name) {
1718
+ this.name = name;
1719
+ }
1720
+ on(...columns$1) {
1721
+ return new UniqueConstraintBuilder(columns$1, this.name);
1722
+ }
1723
+ };
1724
+ var UniqueConstraint = class {
1725
+ constructor(table, columns$1, name) {
1726
+ this.table = table;
1727
+ this.columns = columns$1;
1728
+ this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));
1729
+ }
1730
+ static [entityKind] = "SQLiteUniqueConstraint";
1731
+ columns;
1732
+ name;
1733
+ getName() {
1734
+ return this.name;
1735
+ }
1736
+ };
1737
+
1738
+ //#endregion
1739
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/columns/common.js
1740
+ var SQLiteColumnBuilder = class extends ColumnBuilder {
1741
+ static [entityKind] = "SQLiteColumnBuilder";
1742
+ foreignKeyConfigs = [];
1743
+ references(ref, actions = {}) {
1744
+ this.foreignKeyConfigs.push({
1745
+ ref,
1746
+ actions
1747
+ });
1748
+ return this;
1749
+ }
1750
+ unique(name) {
1751
+ this.config.isUnique = true;
1752
+ this.config.uniqueName = name;
1753
+ return this;
1754
+ }
1755
+ generatedAlwaysAs(as, config) {
1756
+ this.config.generated = {
1757
+ as,
1758
+ type: "always",
1759
+ mode: config?.mode ?? "virtual"
1760
+ };
1761
+ return this;
1762
+ }
1763
+ /** @internal */
1764
+ buildForeignKeys(column, table) {
1765
+ return this.foreignKeyConfigs.map(({ ref, actions }) => {
1766
+ return ((ref2, actions2) => {
1767
+ const builder = new ForeignKeyBuilder(() => {
1768
+ const foreignColumn = ref2();
1769
+ return {
1770
+ columns: [column],
1771
+ foreignColumns: [foreignColumn]
1772
+ };
1773
+ });
1774
+ if (actions2.onUpdate) builder.onUpdate(actions2.onUpdate);
1775
+ if (actions2.onDelete) builder.onDelete(actions2.onDelete);
1776
+ return builder.build(table);
1777
+ })(ref, actions);
1778
+ });
1779
+ }
1780
+ };
1781
+ var SQLiteColumn = class extends Column {
1782
+ constructor(table, config) {
1783
+ if (!config.uniqueName) config.uniqueName = uniqueKeyName(table, [config.name]);
1784
+ super(table, config);
1785
+ this.table = table;
1786
+ }
1787
+ static [entityKind] = "SQLiteColumn";
1788
+ };
1789
+
1790
+ //#endregion
1791
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/columns/blob.js
1792
+ var SQLiteBigIntBuilder = class extends SQLiteColumnBuilder {
1793
+ static [entityKind] = "SQLiteBigIntBuilder";
1794
+ constructor(name) {
1795
+ super(name, "bigint", "SQLiteBigInt");
1796
+ }
1797
+ /** @internal */
1798
+ build(table) {
1799
+ return new SQLiteBigInt(table, this.config);
1800
+ }
1801
+ };
1802
+ var SQLiteBigInt = class extends SQLiteColumn {
1803
+ static [entityKind] = "SQLiteBigInt";
1804
+ getSQLType() {
1805
+ return "blob";
1806
+ }
1807
+ mapFromDriverValue(value) {
1808
+ if (typeof Buffer !== "undefined" && Buffer.from) {
1809
+ const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);
1810
+ return BigInt(buf.toString("utf8"));
1811
+ }
1812
+ return BigInt(textDecoder.decode(value));
1813
+ }
1814
+ mapToDriverValue(value) {
1815
+ return Buffer.from(value.toString());
1816
+ }
1817
+ };
1818
+ var SQLiteBlobJsonBuilder = class extends SQLiteColumnBuilder {
1819
+ static [entityKind] = "SQLiteBlobJsonBuilder";
1820
+ constructor(name) {
1821
+ super(name, "json", "SQLiteBlobJson");
1822
+ }
1823
+ /** @internal */
1824
+ build(table) {
1825
+ return new SQLiteBlobJson(table, this.config);
1826
+ }
1827
+ };
1828
+ var SQLiteBlobJson = class extends SQLiteColumn {
1829
+ static [entityKind] = "SQLiteBlobJson";
1830
+ getSQLType() {
1831
+ return "blob";
1832
+ }
1833
+ mapFromDriverValue(value) {
1834
+ if (typeof Buffer !== "undefined" && Buffer.from) {
1835
+ const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);
1836
+ return JSON.parse(buf.toString("utf8"));
1837
+ }
1838
+ return JSON.parse(textDecoder.decode(value));
1839
+ }
1840
+ mapToDriverValue(value) {
1841
+ return Buffer.from(JSON.stringify(value));
1842
+ }
1843
+ };
1844
+ var SQLiteBlobBufferBuilder = class extends SQLiteColumnBuilder {
1845
+ static [entityKind] = "SQLiteBlobBufferBuilder";
1846
+ constructor(name) {
1847
+ super(name, "buffer", "SQLiteBlobBuffer");
1848
+ }
1849
+ /** @internal */
1850
+ build(table) {
1851
+ return new SQLiteBlobBuffer(table, this.config);
1852
+ }
1853
+ };
1854
+ var SQLiteBlobBuffer = class extends SQLiteColumn {
1855
+ static [entityKind] = "SQLiteBlobBuffer";
1856
+ mapFromDriverValue(value) {
1857
+ if (Buffer.isBuffer(value)) return value;
1858
+ return Buffer.from(value);
1859
+ }
1860
+ getSQLType() {
1861
+ return "blob";
1862
+ }
1863
+ };
1864
+ function blob(a, b) {
1865
+ const { name, config } = getColumnNameAndConfig(a, b);
1866
+ if (config?.mode === "json") return new SQLiteBlobJsonBuilder(name);
1867
+ if (config?.mode === "bigint") return new SQLiteBigIntBuilder(name);
1868
+ return new SQLiteBlobBufferBuilder(name);
1869
+ }
1870
+
1871
+ //#endregion
1872
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/columns/custom.js
1873
+ var SQLiteCustomColumnBuilder = class extends SQLiteColumnBuilder {
1874
+ static [entityKind] = "SQLiteCustomColumnBuilder";
1875
+ constructor(name, fieldConfig, customTypeParams) {
1876
+ super(name, "custom", "SQLiteCustomColumn");
1877
+ this.config.fieldConfig = fieldConfig;
1878
+ this.config.customTypeParams = customTypeParams;
1879
+ }
1880
+ /** @internal */
1881
+ build(table) {
1882
+ return new SQLiteCustomColumn(table, this.config);
1883
+ }
1884
+ };
1885
+ var SQLiteCustomColumn = class extends SQLiteColumn {
1886
+ static [entityKind] = "SQLiteCustomColumn";
1887
+ sqlName;
1888
+ mapTo;
1889
+ mapFrom;
1890
+ constructor(table, config) {
1891
+ super(table, config);
1892
+ this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
1893
+ this.mapTo = config.customTypeParams.toDriver;
1894
+ this.mapFrom = config.customTypeParams.fromDriver;
1895
+ }
1896
+ getSQLType() {
1897
+ return this.sqlName;
1898
+ }
1899
+ mapFromDriverValue(value) {
1900
+ return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
1901
+ }
1902
+ mapToDriverValue(value) {
1903
+ return typeof this.mapTo === "function" ? this.mapTo(value) : value;
1904
+ }
1905
+ };
1906
+ function customType(customTypeParams) {
1907
+ return (a, b) => {
1908
+ const { name, config } = getColumnNameAndConfig(a, b);
1909
+ return new SQLiteCustomColumnBuilder(name, config, customTypeParams);
1910
+ };
1911
+ }
1912
+
1913
+ //#endregion
1914
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/columns/integer.js
1915
+ var SQLiteBaseIntegerBuilder = class extends SQLiteColumnBuilder {
1916
+ static [entityKind] = "SQLiteBaseIntegerBuilder";
1917
+ constructor(name, dataType, columnType) {
1918
+ super(name, dataType, columnType);
1919
+ this.config.autoIncrement = false;
1920
+ }
1921
+ primaryKey(config) {
1922
+ if (config?.autoIncrement) this.config.autoIncrement = true;
1923
+ this.config.hasDefault = true;
1924
+ return super.primaryKey();
1925
+ }
1926
+ };
1927
+ var SQLiteBaseInteger = class extends SQLiteColumn {
1928
+ static [entityKind] = "SQLiteBaseInteger";
1929
+ autoIncrement = this.config.autoIncrement;
1930
+ getSQLType() {
1931
+ return "integer";
1932
+ }
1933
+ };
1934
+ var SQLiteIntegerBuilder = class extends SQLiteBaseIntegerBuilder {
1935
+ static [entityKind] = "SQLiteIntegerBuilder";
1936
+ constructor(name) {
1937
+ super(name, "number", "SQLiteInteger");
1938
+ }
1939
+ build(table) {
1940
+ return new SQLiteInteger(table, this.config);
1941
+ }
1942
+ };
1943
+ var SQLiteInteger = class extends SQLiteBaseInteger {
1944
+ static [entityKind] = "SQLiteInteger";
1945
+ };
1946
+ var SQLiteTimestampBuilder = class extends SQLiteBaseIntegerBuilder {
1947
+ static [entityKind] = "SQLiteTimestampBuilder";
1948
+ constructor(name, mode) {
1949
+ super(name, "date", "SQLiteTimestamp");
1950
+ this.config.mode = mode;
1951
+ }
1952
+ /**
1953
+ * @deprecated Use `default()` with your own expression instead.
1954
+ *
1955
+ * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.
1956
+ */
1957
+ defaultNow() {
1958
+ return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);
1959
+ }
1960
+ build(table) {
1961
+ return new SQLiteTimestamp(table, this.config);
1962
+ }
1963
+ };
1964
+ var SQLiteTimestamp = class extends SQLiteBaseInteger {
1965
+ static [entityKind] = "SQLiteTimestamp";
1966
+ mode = this.config.mode;
1967
+ mapFromDriverValue(value) {
1968
+ if (this.config.mode === "timestamp") return /* @__PURE__ */ new Date(value * 1e3);
1969
+ return new Date(value);
1970
+ }
1971
+ mapToDriverValue(value) {
1972
+ const unix = value.getTime();
1973
+ if (this.config.mode === "timestamp") return Math.floor(unix / 1e3);
1974
+ return unix;
1975
+ }
1976
+ };
1977
+ var SQLiteBooleanBuilder = class extends SQLiteBaseIntegerBuilder {
1978
+ static [entityKind] = "SQLiteBooleanBuilder";
1979
+ constructor(name, mode) {
1980
+ super(name, "boolean", "SQLiteBoolean");
1981
+ this.config.mode = mode;
1982
+ }
1983
+ build(table) {
1984
+ return new SQLiteBoolean(table, this.config);
1985
+ }
1986
+ };
1987
+ var SQLiteBoolean = class extends SQLiteBaseInteger {
1988
+ static [entityKind] = "SQLiteBoolean";
1989
+ mode = this.config.mode;
1990
+ mapFromDriverValue(value) {
1991
+ return Number(value) === 1;
1992
+ }
1993
+ mapToDriverValue(value) {
1994
+ return value ? 1 : 0;
1995
+ }
1996
+ };
1997
+ function integer(a, b) {
1998
+ const { name, config } = getColumnNameAndConfig(a, b);
1999
+ if (config?.mode === "timestamp" || config?.mode === "timestamp_ms") return new SQLiteTimestampBuilder(name, config.mode);
2000
+ if (config?.mode === "boolean") return new SQLiteBooleanBuilder(name, config.mode);
2001
+ return new SQLiteIntegerBuilder(name);
2002
+ }
2003
+
2004
+ //#endregion
2005
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
2006
+ var SQLiteNumericBuilder = class extends SQLiteColumnBuilder {
2007
+ static [entityKind] = "SQLiteNumericBuilder";
2008
+ constructor(name) {
2009
+ super(name, "string", "SQLiteNumeric");
2010
+ }
2011
+ /** @internal */
2012
+ build(table) {
2013
+ return new SQLiteNumeric(table, this.config);
2014
+ }
2015
+ };
2016
+ var SQLiteNumeric = class extends SQLiteColumn {
2017
+ static [entityKind] = "SQLiteNumeric";
2018
+ mapFromDriverValue(value) {
2019
+ if (typeof value === "string") return value;
2020
+ return String(value);
2021
+ }
2022
+ getSQLType() {
2023
+ return "numeric";
2024
+ }
2025
+ };
2026
+ var SQLiteNumericNumberBuilder = class extends SQLiteColumnBuilder {
2027
+ static [entityKind] = "SQLiteNumericNumberBuilder";
2028
+ constructor(name) {
2029
+ super(name, "number", "SQLiteNumericNumber");
2030
+ }
2031
+ /** @internal */
2032
+ build(table) {
2033
+ return new SQLiteNumericNumber(table, this.config);
2034
+ }
2035
+ };
2036
+ var SQLiteNumericNumber = class extends SQLiteColumn {
2037
+ static [entityKind] = "SQLiteNumericNumber";
2038
+ mapFromDriverValue(value) {
2039
+ if (typeof value === "number") return value;
2040
+ return Number(value);
2041
+ }
2042
+ mapToDriverValue = String;
2043
+ getSQLType() {
2044
+ return "numeric";
2045
+ }
2046
+ };
2047
+ var SQLiteNumericBigIntBuilder = class extends SQLiteColumnBuilder {
2048
+ static [entityKind] = "SQLiteNumericBigIntBuilder";
2049
+ constructor(name) {
2050
+ super(name, "bigint", "SQLiteNumericBigInt");
2051
+ }
2052
+ /** @internal */
2053
+ build(table) {
2054
+ return new SQLiteNumericBigInt(table, this.config);
2055
+ }
2056
+ };
2057
+ var SQLiteNumericBigInt = class extends SQLiteColumn {
2058
+ static [entityKind] = "SQLiteNumericBigInt";
2059
+ mapFromDriverValue = BigInt;
2060
+ mapToDriverValue = String;
2061
+ getSQLType() {
2062
+ return "numeric";
2063
+ }
2064
+ };
2065
+ function numeric(a, b) {
2066
+ const { name, config } = getColumnNameAndConfig(a, b);
2067
+ const mode = config?.mode;
2068
+ return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);
2069
+ }
2070
+
2071
+ //#endregion
2072
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/columns/real.js
2073
+ var SQLiteRealBuilder = class extends SQLiteColumnBuilder {
2074
+ static [entityKind] = "SQLiteRealBuilder";
2075
+ constructor(name) {
2076
+ super(name, "number", "SQLiteReal");
2077
+ }
2078
+ /** @internal */
2079
+ build(table) {
2080
+ return new SQLiteReal(table, this.config);
2081
+ }
2082
+ };
2083
+ var SQLiteReal = class extends SQLiteColumn {
2084
+ static [entityKind] = "SQLiteReal";
2085
+ getSQLType() {
2086
+ return "real";
2087
+ }
2088
+ };
2089
+ function real(name) {
2090
+ return new SQLiteRealBuilder(name ?? "");
2091
+ }
2092
+
2093
+ //#endregion
2094
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/columns/text.js
2095
+ var SQLiteTextBuilder = class extends SQLiteColumnBuilder {
2096
+ static [entityKind] = "SQLiteTextBuilder";
2097
+ constructor(name, config) {
2098
+ super(name, "string", "SQLiteText");
2099
+ this.config.enumValues = config.enum;
2100
+ this.config.length = config.length;
2101
+ }
2102
+ /** @internal */
2103
+ build(table) {
2104
+ return new SQLiteText(table, this.config);
2105
+ }
2106
+ };
2107
+ var SQLiteText = class extends SQLiteColumn {
2108
+ static [entityKind] = "SQLiteText";
2109
+ enumValues = this.config.enumValues;
2110
+ length = this.config.length;
2111
+ constructor(table, config) {
2112
+ super(table, config);
2113
+ }
2114
+ getSQLType() {
2115
+ return `text${this.config.length ? `(${this.config.length})` : ""}`;
2116
+ }
2117
+ };
2118
+ var SQLiteTextJsonBuilder = class extends SQLiteColumnBuilder {
2119
+ static [entityKind] = "SQLiteTextJsonBuilder";
2120
+ constructor(name) {
2121
+ super(name, "json", "SQLiteTextJson");
2122
+ }
2123
+ /** @internal */
2124
+ build(table) {
2125
+ return new SQLiteTextJson(table, this.config);
2126
+ }
2127
+ };
2128
+ var SQLiteTextJson = class extends SQLiteColumn {
2129
+ static [entityKind] = "SQLiteTextJson";
2130
+ getSQLType() {
2131
+ return "text";
2132
+ }
2133
+ mapFromDriverValue(value) {
2134
+ return JSON.parse(value);
2135
+ }
2136
+ mapToDriverValue(value) {
2137
+ return JSON.stringify(value);
2138
+ }
2139
+ };
2140
+ function text(a, b = {}) {
2141
+ const { name, config } = getColumnNameAndConfig(a, b);
2142
+ if (config.mode === "json") return new SQLiteTextJsonBuilder(name);
2143
+ return new SQLiteTextBuilder(name, config);
2144
+ }
2145
+
2146
+ //#endregion
2147
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/columns/all.js
2148
+ function getSQLiteColumnBuilders() {
2149
+ return {
2150
+ blob,
2151
+ customType,
2152
+ integer,
2153
+ numeric,
2154
+ real,
2155
+ text
2156
+ };
2157
+ }
2158
+
2159
+ //#endregion
2160
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/table.js
2161
+ const InlineForeignKeys = Symbol.for("drizzle:SQLiteInlineForeignKeys");
2162
+ var SQLiteTable = class extends Table {
2163
+ static [entityKind] = "SQLiteTable";
2164
+ /** @internal */
2165
+ static Symbol = Object.assign({}, Table.Symbol, { InlineForeignKeys });
2166
+ /** @internal */
2167
+ [Table.Symbol.Columns];
2168
+ /** @internal */
2169
+ [InlineForeignKeys] = [];
2170
+ /** @internal */
2171
+ [Table.Symbol.ExtraConfigBuilder] = void 0;
2172
+ };
2173
+ function sqliteTableBase(name, columns$1, extraConfig, schema, baseName = name) {
2174
+ const rawTable = new SQLiteTable(name, schema, baseName);
2175
+ const parsedColumns = typeof columns$1 === "function" ? columns$1(getSQLiteColumnBuilders()) : columns$1;
2176
+ const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
2177
+ const colBuilder = colBuilderBase;
2178
+ colBuilder.setName(name2);
2179
+ const column = colBuilder.build(rawTable);
2180
+ rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
2181
+ return [name2, column];
2182
+ }));
2183
+ const table = Object.assign(rawTable, builtColumns);
2184
+ table[Table.Symbol.Columns] = builtColumns;
2185
+ table[Table.Symbol.ExtraConfigColumns] = builtColumns;
2186
+ if (extraConfig) table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
2187
+ return table;
2188
+ }
2189
+ const sqliteTable = (name, columns$1, extraConfig) => {
2190
+ return sqliteTableBase(name, columns$1, extraConfig);
2191
+ };
2192
+
2193
+ //#endregion
2194
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/primary-keys.js
2195
+ function primaryKey(...config) {
2196
+ if (config[0].columns) return new PrimaryKeyBuilder(config[0].columns, config[0].name);
2197
+ return new PrimaryKeyBuilder(config);
2198
+ }
2199
+ var PrimaryKeyBuilder = class {
2200
+ static [entityKind] = "SQLitePrimaryKeyBuilder";
2201
+ /** @internal */
2202
+ columns;
2203
+ /** @internal */
2204
+ name;
2205
+ constructor(columns$1, name) {
2206
+ this.columns = columns$1;
2207
+ this.name = name;
2208
+ }
2209
+ /** @internal */
2210
+ build(table) {
2211
+ return new PrimaryKey(table, this.columns, this.name);
2212
+ }
2213
+ };
2214
+ var PrimaryKey = class {
2215
+ constructor(table, columns$1, name) {
2216
+ this.table = table;
2217
+ this.columns = columns$1;
2218
+ this.name = name;
2219
+ }
2220
+ static [entityKind] = "SQLitePrimaryKey";
2221
+ columns;
2222
+ name;
2223
+ getName() {
2224
+ return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
2225
+ }
2226
+ };
2227
+
2228
+ //#endregion
2229
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/utils.js
2230
+ function extractUsedTable(table) {
2231
+ if (is(table, SQLiteTable)) return [`${table[Table.Symbol.BaseName]}`];
2232
+ if (is(table, Subquery)) return table._.usedTables ?? [];
2233
+ if (is(table, SQL)) return table.usedTables ?? [];
2234
+ return [];
2235
+ }
2236
+
2237
+ //#endregion
2238
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js
2239
+ var SQLiteDeleteBase = class extends QueryPromise {
2240
+ constructor(table, session, dialect$1, withList) {
2241
+ super();
2242
+ this.table = table;
2243
+ this.session = session;
2244
+ this.dialect = dialect$1;
2245
+ this.config = {
2246
+ table,
2247
+ withList
2248
+ };
2249
+ }
2250
+ static [entityKind] = "SQLiteDelete";
2251
+ /** @internal */
2252
+ config;
2253
+ /**
2254
+ * Adds a `where` clause to the query.
2255
+ *
2256
+ * Calling this method will delete only those rows that fulfill a specified condition.
2257
+ *
2258
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
2259
+ *
2260
+ * @param where the `where` clause.
2261
+ *
2262
+ * @example
2263
+ * You can use conditional operators and `sql function` to filter the rows to be deleted.
2264
+ *
2265
+ * ```ts
2266
+ * // Delete all cars with green color
2267
+ * db.delete(cars).where(eq(cars.color, 'green'));
2268
+ * // or
2269
+ * db.delete(cars).where(sql`${cars.color} = 'green'`)
2270
+ * ```
2271
+ *
2272
+ * You can logically combine conditional operators with `and()` and `or()` operators:
2273
+ *
2274
+ * ```ts
2275
+ * // Delete all BMW cars with a green color
2276
+ * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
2277
+ *
2278
+ * // Delete all cars with the green or blue color
2279
+ * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
2280
+ * ```
2281
+ */
2282
+ where(where) {
2283
+ this.config.where = where;
2284
+ return this;
2285
+ }
2286
+ orderBy(...columns$1) {
2287
+ if (typeof columns$1[0] === "function") {
2288
+ const orderBy = columns$1[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
2289
+ sqlAliasedBehavior: "alias",
2290
+ sqlBehavior: "sql"
2291
+ })));
2292
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
2293
+ this.config.orderBy = orderByArray;
2294
+ } else {
2295
+ const orderByArray = columns$1;
2296
+ this.config.orderBy = orderByArray;
2297
+ }
2298
+ return this;
2299
+ }
2300
+ limit(limit) {
2301
+ this.config.limit = limit;
2302
+ return this;
2303
+ }
2304
+ returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
2305
+ this.config.returning = orderSelectedFields(fields);
2306
+ return this;
2307
+ }
2308
+ /** @internal */
2309
+ getSQL() {
2310
+ return this.dialect.buildDeleteQuery(this.config);
2311
+ }
2312
+ toSQL() {
2313
+ const { typings: _typings,...rest } = this.dialect.sqlToQuery(this.getSQL());
2314
+ return rest;
2315
+ }
2316
+ /** @internal */
2317
+ _prepare(isOneTimeQuery = true) {
2318
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, void 0, {
2319
+ type: "delete",
2320
+ tables: extractUsedTable(this.config.table)
2321
+ });
2322
+ }
2323
+ prepare() {
2324
+ return this._prepare(false);
2325
+ }
2326
+ run = (placeholderValues) => {
2327
+ return this._prepare().run(placeholderValues);
2328
+ };
2329
+ all = (placeholderValues) => {
2330
+ return this._prepare().all(placeholderValues);
2331
+ };
2332
+ get = (placeholderValues) => {
2333
+ return this._prepare().get(placeholderValues);
2334
+ };
2335
+ values = (placeholderValues) => {
2336
+ return this._prepare().values(placeholderValues);
2337
+ };
2338
+ async execute(placeholderValues) {
2339
+ return this._prepare().execute(placeholderValues);
2340
+ }
2341
+ $dynamic() {
2342
+ return this;
2343
+ }
2344
+ };
2345
+
2346
+ //#endregion
2347
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/casing.js
2348
+ function toSnakeCase(input) {
2349
+ return (input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []).map((word) => word.toLowerCase()).join("_");
2350
+ }
2351
+ function toCamelCase(input) {
2352
+ return (input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []).reduce((acc, word, i) => {
2353
+ return acc + (i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`);
2354
+ }, "");
2355
+ }
2356
+ function noopCase(input) {
2357
+ return input;
2358
+ }
2359
+ var CasingCache = class {
2360
+ static [entityKind] = "CasingCache";
2361
+ /** @internal */
2362
+ cache = {};
2363
+ cachedTables = {};
2364
+ convert;
2365
+ constructor(casing) {
2366
+ this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
2367
+ }
2368
+ getColumnCasing(column) {
2369
+ if (!column.keyAsName) return column.name;
2370
+ const key = `${column.table[Table.Symbol.Schema] ?? "public"}.${column.table[Table.Symbol.OriginalName]}.${column.name}`;
2371
+ if (!this.cache[key]) this.cacheTable(column.table);
2372
+ return this.cache[key];
2373
+ }
2374
+ cacheTable(table) {
2375
+ const tableKey = `${table[Table.Symbol.Schema] ?? "public"}.${table[Table.Symbol.OriginalName]}`;
2376
+ if (!this.cachedTables[tableKey]) {
2377
+ for (const column of Object.values(table[Table.Symbol.Columns])) {
2378
+ const columnKey = `${tableKey}.${column.name}`;
2379
+ this.cache[columnKey] = this.convert(column.name);
2380
+ }
2381
+ this.cachedTables[tableKey] = true;
2382
+ }
2383
+ }
2384
+ clearCache() {
2385
+ this.cache = {};
2386
+ this.cachedTables = {};
2387
+ }
2388
+ };
2389
+
2390
+ //#endregion
2391
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/errors.js
2392
+ var DrizzleError = class extends Error {
2393
+ static [entityKind] = "DrizzleError";
2394
+ constructor({ message, cause }) {
2395
+ super(message);
2396
+ this.name = "DrizzleError";
2397
+ this.cause = cause;
2398
+ }
2399
+ };
2400
+ var DrizzleQueryError = class DrizzleQueryError extends Error {
2401
+ constructor(query, params, cause) {
2402
+ super(`Failed query: ${query}
2403
+ params: ${params}`);
2404
+ this.query = query;
2405
+ this.params = params;
2406
+ this.cause = cause;
2407
+ Error.captureStackTrace(this, DrizzleQueryError);
2408
+ if (cause) this.cause = cause;
2409
+ }
2410
+ };
2411
+ var TransactionRollbackError = class extends DrizzleError {
2412
+ static [entityKind] = "TransactionRollbackError";
2413
+ constructor() {
2414
+ super({ message: "Rollback" });
2415
+ }
2416
+ };
2417
+
2418
+ //#endregion
2419
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/view-base.js
2420
+ var SQLiteViewBase = class extends View {
2421
+ static [entityKind] = "SQLiteViewBase";
2422
+ };
2423
+
2424
+ //#endregion
2425
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/dialect.js
2426
+ var SQLiteDialect = class {
2427
+ static [entityKind] = "SQLiteDialect";
2428
+ /** @internal */
2429
+ casing;
2430
+ constructor(config) {
2431
+ this.casing = new CasingCache(config?.casing);
2432
+ }
2433
+ escapeName(name) {
2434
+ return `"${name}"`;
2435
+ }
2436
+ escapeParam(_num) {
2437
+ return "?";
2438
+ }
2439
+ escapeString(str) {
2440
+ return `'${str.replace(/'/g, "''")}'`;
2441
+ }
2442
+ buildWithCTE(queries) {
2443
+ if (!queries?.length) return void 0;
2444
+ const withSqlChunks = [sql`with `];
2445
+ for (const [i, w] of queries.entries()) {
2446
+ withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
2447
+ if (i < queries.length - 1) withSqlChunks.push(sql`, `);
2448
+ }
2449
+ withSqlChunks.push(sql` `);
2450
+ return sql.join(withSqlChunks);
2451
+ }
2452
+ buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) {
2453
+ const withSql = this.buildWithCTE(withList);
2454
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
2455
+ return sql`${withSql}delete from ${table}${where ? sql` where ${where}` : void 0}${returningSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}`;
2456
+ }
2457
+ buildUpdateSet(table, set) {
2458
+ const tableColumns = table[Table.Symbol.Columns];
2459
+ const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0);
2460
+ const setSize = columnNames.length;
2461
+ return sql.join(columnNames.flatMap((colName, i) => {
2462
+ const col = tableColumns[colName];
2463
+ const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
2464
+ const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
2465
+ if (i < setSize - 1) return [res, sql.raw(", ")];
2466
+ return [res];
2467
+ }));
2468
+ }
2469
+ buildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }) {
2470
+ const withSql = this.buildWithCTE(withList);
2471
+ const setSql = this.buildUpdateSet(table, set);
2472
+ const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
2473
+ const joinsSql = this.buildJoins(joins);
2474
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
2475
+ return sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${where ? sql` where ${where}` : void 0}${returningSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}`;
2476
+ }
2477
+ /**
2478
+ * Builds selection SQL with provided fields/expressions
2479
+ *
2480
+ * Examples:
2481
+ *
2482
+ * `select <selection> from`
2483
+ *
2484
+ * `insert ... returning <selection>`
2485
+ *
2486
+ * If `isSingleTable` is true, then columns won't be prefixed with table name
2487
+ */
2488
+ buildSelection(fields, { isSingleTable = false } = {}) {
2489
+ const columnsLen = fields.length;
2490
+ const chunks = fields.flatMap(({ field }, i) => {
2491
+ const chunk = [];
2492
+ if (is(field, SQL.Aliased) && field.isSelectionField) chunk.push(sql.identifier(field.fieldAlias));
2493
+ else if (is(field, SQL.Aliased) || is(field, SQL)) {
2494
+ const query = is(field, SQL.Aliased) ? field.sql : field;
2495
+ if (isSingleTable) chunk.push(new SQL(query.queryChunks.map((c) => {
2496
+ if (is(c, Column)) return sql.identifier(this.casing.getColumnCasing(c));
2497
+ return c;
2498
+ })));
2499
+ else chunk.push(query);
2500
+ if (is(field, SQL.Aliased)) chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
2501
+ } else if (is(field, Column)) {
2502
+ const tableName = field.table[Table.Symbol.Name];
2503
+ if (field.columnType === "SQLiteNumericBigInt") if (isSingleTable) chunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
2504
+ else chunk.push(sql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
2505
+ else if (isSingleTable) chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
2506
+ else chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);
2507
+ }
2508
+ if (i < columnsLen - 1) chunk.push(sql`, `);
2509
+ return chunk;
2510
+ });
2511
+ return sql.join(chunks);
2512
+ }
2513
+ buildJoins(joins) {
2514
+ if (!joins || joins.length === 0) return;
2515
+ const joinsArray = [];
2516
+ if (joins) for (const [index, joinMeta] of joins.entries()) {
2517
+ if (index === 0) joinsArray.push(sql` `);
2518
+ const table = joinMeta.table;
2519
+ const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
2520
+ if (is(table, SQLiteTable)) {
2521
+ const tableName = table[SQLiteTable.Symbol.Name];
2522
+ const tableSchema = table[SQLiteTable.Symbol.Schema];
2523
+ const origTableName = table[SQLiteTable.Symbol.OriginalName];
2524
+ const alias = tableName === origTableName ? void 0 : joinMeta.alias;
2525
+ joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);
2526
+ } else joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`);
2527
+ if (index < joins.length - 1) joinsArray.push(sql` `);
2528
+ }
2529
+ return sql.join(joinsArray);
2530
+ }
2531
+ buildLimit(limit) {
2532
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
2533
+ }
2534
+ buildOrderBy(orderBy) {
2535
+ const orderByList = [];
2536
+ if (orderBy) for (const [index, orderByValue] of orderBy.entries()) {
2537
+ orderByList.push(orderByValue);
2538
+ if (index < orderBy.length - 1) orderByList.push(sql`, `);
2539
+ }
2540
+ return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
2541
+ }
2542
+ buildFromTable(table) {
2543
+ if (is(table, Table) && table[Table.Symbol.IsAlias]) return sql`${sql`${sql.identifier(table[Table.Symbol.Schema] ?? "")}.`.if(table[Table.Symbol.Schema])}${sql.identifier(table[Table.Symbol.OriginalName])} ${sql.identifier(table[Table.Symbol.Name])}`;
2544
+ return table;
2545
+ }
2546
+ buildSelectQuery({ withList, fields, fieldsFlat, where, having, table, joins, orderBy, groupBy, limit, offset, distinct, setOperators }) {
2547
+ const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
2548
+ for (const f of fieldsList) if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, SQLiteViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])))(f.field.table)) {
2549
+ const tableName = getTableName(f.field.table);
2550
+ throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`);
2551
+ }
2552
+ const isSingleTable = !joins || joins.length === 0;
2553
+ const withSql = this.buildWithCTE(withList);
2554
+ const distinctSql = distinct ? sql` distinct` : void 0;
2555
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
2556
+ const tableSql = this.buildFromTable(table);
2557
+ const joinsSql = this.buildJoins(joins);
2558
+ const whereSql = where ? sql` where ${where}` : void 0;
2559
+ const havingSql = having ? sql` having ${having}` : void 0;
2560
+ const groupByList = [];
2561
+ if (groupBy) for (const [index, groupByValue] of groupBy.entries()) {
2562
+ groupByList.push(groupByValue);
2563
+ if (index < groupBy.length - 1) groupByList.push(sql`, `);
2564
+ }
2565
+ const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0}${havingSql}${this.buildOrderBy(orderBy)}${this.buildLimit(limit)}${offset ? sql` offset ${offset}` : void 0}`;
2566
+ if (setOperators.length > 0) return this.buildSetOperations(finalQuery, setOperators);
2567
+ return finalQuery;
2568
+ }
2569
+ buildSetOperations(leftSelect, setOperators) {
2570
+ const [setOperator, ...rest] = setOperators;
2571
+ if (!setOperator) throw new Error("Cannot pass undefined values to any set operator");
2572
+ if (rest.length === 0) return this.buildSetOperationQuery({
2573
+ leftSelect,
2574
+ setOperator
2575
+ });
2576
+ return this.buildSetOperations(this.buildSetOperationQuery({
2577
+ leftSelect,
2578
+ setOperator
2579
+ }), rest);
2580
+ }
2581
+ buildSetOperationQuery({ leftSelect, setOperator: { type, isAll, rightSelect, limit, orderBy, offset } }) {
2582
+ const leftChunk = sql`${leftSelect.getSQL()} `;
2583
+ const rightChunk = sql`${rightSelect.getSQL()}`;
2584
+ let orderBySql;
2585
+ if (orderBy && orderBy.length > 0) {
2586
+ const orderByValues = [];
2587
+ for (const singleOrderBy of orderBy) if (is(singleOrderBy, SQLiteColumn)) orderByValues.push(sql.identifier(singleOrderBy.name));
2588
+ else if (is(singleOrderBy, SQL)) {
2589
+ for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
2590
+ const chunk = singleOrderBy.queryChunks[i];
2591
+ if (is(chunk, SQLiteColumn)) singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
2592
+ }
2593
+ orderByValues.push(sql`${singleOrderBy}`);
2594
+ } else orderByValues.push(sql`${singleOrderBy}`);
2595
+ orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
2596
+ }
2597
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
2598
+ const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
2599
+ const offsetSql = offset ? sql` offset ${offset}` : void 0;
2600
+ return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
2601
+ }
2602
+ buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select }) {
2603
+ const valuesSqlList = [];
2604
+ const columns$1 = table[Table.Symbol.Columns];
2605
+ const colEntries = Object.entries(columns$1).filter(([_$1, col]) => !col.shouldDisableInsert());
2606
+ const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));
2607
+ if (select) {
2608
+ const select2 = valuesOrSelect;
2609
+ if (is(select2, SQL)) valuesSqlList.push(select2);
2610
+ else valuesSqlList.push(select2.getSQL());
2611
+ } else {
2612
+ const values = valuesOrSelect;
2613
+ valuesSqlList.push(sql.raw("values "));
2614
+ for (const [valueIndex, value] of values.entries()) {
2615
+ const valueList = [];
2616
+ for (const [fieldName, col] of colEntries) {
2617
+ const colValue = value[fieldName];
2618
+ if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
2619
+ let defaultValue;
2620
+ if (col.default !== null && col.default !== void 0) defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
2621
+ else if (col.defaultFn !== void 0) {
2622
+ const defaultFnResult = col.defaultFn();
2623
+ defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
2624
+ } else if (!col.default && col.onUpdateFn !== void 0) {
2625
+ const onUpdateFnResult = col.onUpdateFn();
2626
+ defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
2627
+ } else defaultValue = sql`null`;
2628
+ valueList.push(defaultValue);
2629
+ } else valueList.push(colValue);
2630
+ }
2631
+ valuesSqlList.push(valueList);
2632
+ if (valueIndex < values.length - 1) valuesSqlList.push(sql`, `);
2633
+ }
2634
+ }
2635
+ const withSql = this.buildWithCTE(withList);
2636
+ const valuesSql = sql.join(valuesSqlList);
2637
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
2638
+ return sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflict?.length ? sql.join(onConflict) : void 0}${returningSql}`;
2639
+ }
2640
+ sqlToQuery(sql2, invokeSource) {
2641
+ return sql2.toQuery({
2642
+ casing: this.casing,
2643
+ escapeName: this.escapeName,
2644
+ escapeParam: this.escapeParam,
2645
+ escapeString: this.escapeString,
2646
+ invokeSource
2647
+ });
2648
+ }
2649
+ buildRelationalQuery({ fullSchema, schema, tableNamesMap, table, tableConfig, queryConfig: config, tableAlias, nestedQueryRelation, joinOn }) {
2650
+ let selection = [];
2651
+ let limit, offset, orderBy = [], where;
2652
+ const joins = [];
2653
+ if (config === true) selection = Object.entries(tableConfig.columns).map(([key, value]) => ({
2654
+ dbKey: value.name,
2655
+ tsKey: key,
2656
+ field: aliasedTableColumn(value, tableAlias),
2657
+ relationTableTsKey: void 0,
2658
+ isJson: false,
2659
+ selection: []
2660
+ }));
2661
+ else {
2662
+ const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
2663
+ if (config.where) {
2664
+ const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
2665
+ where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
2666
+ }
2667
+ const fieldsSelection = [];
2668
+ let selectedColumns = [];
2669
+ if (config.columns) {
2670
+ let isIncludeMode = false;
2671
+ for (const [field, value] of Object.entries(config.columns)) {
2672
+ if (value === void 0) continue;
2673
+ if (field in tableConfig.columns) {
2674
+ if (!isIncludeMode && value === true) isIncludeMode = true;
2675
+ selectedColumns.push(field);
2676
+ }
2677
+ }
2678
+ if (selectedColumns.length > 0) selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
2679
+ } else selectedColumns = Object.keys(tableConfig.columns);
2680
+ for (const field of selectedColumns) {
2681
+ const column = tableConfig.columns[field];
2682
+ fieldsSelection.push({
2683
+ tsKey: field,
2684
+ value: column
2685
+ });
2686
+ }
2687
+ let selectedRelations = [];
2688
+ if (config.with) selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({
2689
+ tsKey,
2690
+ queryConfig,
2691
+ relation: tableConfig.relations[tsKey]
2692
+ }));
2693
+ let extras;
2694
+ if (config.extras) {
2695
+ extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
2696
+ for (const [tsKey, value] of Object.entries(extras)) fieldsSelection.push({
2697
+ tsKey,
2698
+ value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
2699
+ });
2700
+ }
2701
+ for (const { tsKey, value } of fieldsSelection) selection.push({
2702
+ dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
2703
+ tsKey,
2704
+ field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
2705
+ relationTableTsKey: void 0,
2706
+ isJson: false,
2707
+ selection: []
2708
+ });
2709
+ let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
2710
+ if (!Array.isArray(orderByOrig)) orderByOrig = [orderByOrig];
2711
+ orderBy = orderByOrig.map((orderByValue) => {
2712
+ if (is(orderByValue, Column)) return aliasedTableColumn(orderByValue, tableAlias);
2713
+ return mapColumnsInSQLToAlias(orderByValue, tableAlias);
2714
+ });
2715
+ limit = config.limit;
2716
+ offset = config.offset;
2717
+ for (const { tsKey: selectedRelationTsKey, queryConfig: selectedRelationConfigValue, relation } of selectedRelations) {
2718
+ const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
2719
+ const relationTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
2720
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
2721
+ const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias))));
2722
+ const builtRelation = this.buildRelationalQuery({
2723
+ fullSchema,
2724
+ schema,
2725
+ tableNamesMap,
2726
+ table: fullSchema[relationTableTsName],
2727
+ tableConfig: schema[relationTableTsName],
2728
+ queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : {
2729
+ ...selectedRelationConfigValue,
2730
+ limit: 1
2731
+ } : selectedRelationConfigValue,
2732
+ tableAlias: relationTableAlias,
2733
+ joinOn: joinOn2,
2734
+ nestedQueryRelation: relation
2735
+ });
2736
+ const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
2737
+ selection.push({
2738
+ dbKey: selectedRelationTsKey,
2739
+ tsKey: selectedRelationTsKey,
2740
+ field,
2741
+ relationTableTsKey: relationTableTsName,
2742
+ isJson: true,
2743
+ selection: builtRelation.selection
2744
+ });
2745
+ }
2746
+ }
2747
+ if (selection.length === 0) throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.` });
2748
+ let result;
2749
+ where = and(joinOn, where);
2750
+ if (nestedQueryRelation) {
2751
+ let field = sql`json_array(${sql.join(selection.map(({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`;
2752
+ if (is(nestedQueryRelation, Many)) field = sql`coalesce(json_group_array(${field}), json_array())`;
2753
+ const nestedSelection = [{
2754
+ dbKey: "data",
2755
+ tsKey: "data",
2756
+ field: field.as("data"),
2757
+ isJson: true,
2758
+ relationTableTsKey: tableConfig.tsName,
2759
+ selection
2760
+ }];
2761
+ if (limit !== void 0 || offset !== void 0 || orderBy.length > 0) {
2762
+ result = this.buildSelectQuery({
2763
+ table: aliasedTable(table, tableAlias),
2764
+ fields: {},
2765
+ fieldsFlat: [{
2766
+ path: [],
2767
+ field: sql.raw("*")
2768
+ }],
2769
+ where,
2770
+ limit,
2771
+ offset,
2772
+ orderBy,
2773
+ setOperators: []
2774
+ });
2775
+ where = void 0;
2776
+ limit = void 0;
2777
+ offset = void 0;
2778
+ orderBy = void 0;
2779
+ } else result = aliasedTable(table, tableAlias);
2780
+ result = this.buildSelectQuery({
2781
+ table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),
2782
+ fields: {},
2783
+ fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
2784
+ path: [],
2785
+ field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
2786
+ })),
2787
+ joins,
2788
+ where,
2789
+ limit,
2790
+ offset,
2791
+ orderBy,
2792
+ setOperators: []
2793
+ });
2794
+ } else result = this.buildSelectQuery({
2795
+ table: aliasedTable(table, tableAlias),
2796
+ fields: {},
2797
+ fieldsFlat: selection.map(({ field }) => ({
2798
+ path: [],
2799
+ field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
2800
+ })),
2801
+ joins,
2802
+ where,
2803
+ limit,
2804
+ offset,
2805
+ orderBy,
2806
+ setOperators: []
2807
+ });
2808
+ return {
2809
+ tableTsKey: tableConfig.tsName,
2810
+ sql: result,
2811
+ selection
2812
+ };
2813
+ }
2814
+ };
2815
+ var SQLiteSyncDialect = class extends SQLiteDialect {
2816
+ static [entityKind] = "SQLiteSyncDialect";
2817
+ migrate(migrations, session, config) {
2818
+ const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
2819
+ const migrationTableCreate = sql`
2820
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
4
2821
  id SERIAL PRIMARY KEY,
5
2822
  hash text NOT NULL,
6
2823
  created_at numeric
7
2824
  )
8
- `;t.run(n);let u=t.values(o`SELECT id, hash, created_at FROM ${o.identifier(i)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;t.run(o`BEGIN`);try{for(let f of e)if(!u||Number(u[2])<f.folderMillis){for(let d of f.sql)t.run(o.raw(d));t.run(o`INSERT INTO ${o.identifier(i)} ("hash", "created_at") VALUES(${f.hash}, ${f.folderMillis})`)}t.run(o`COMMIT`)}catch(f){throw t.run(o`ROLLBACK`),f}}},Ns=class extends ce{static[l]="SQLiteAsyncDialect";async migrate(e,t,s){let i=s===void 0||typeof s=="string"?"__drizzle_migrations":s.migrationsTable??"__drizzle_migrations",n=o`
9
- CREATE TABLE IF NOT EXISTS ${o.identifier(i)} (
2825
+ `;
2826
+ session.run(migrationTableCreate);
2827
+ const lastDbMigration = session.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`)[0] ?? void 0;
2828
+ session.run(sql`BEGIN`);
2829
+ try {
2830
+ for (const migration of migrations) if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
2831
+ for (const stmt of migration.sql) session.run(sql.raw(stmt));
2832
+ session.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
2833
+ }
2834
+ session.run(sql`COMMIT`);
2835
+ } catch (e) {
2836
+ session.run(sql`ROLLBACK`);
2837
+ throw e;
2838
+ }
2839
+ }
2840
+ };
2841
+ var SQLiteAsyncDialect = class extends SQLiteDialect {
2842
+ static [entityKind] = "SQLiteAsyncDialect";
2843
+ async migrate(migrations, session, config) {
2844
+ const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
2845
+ const migrationTableCreate = sql`
2846
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
10
2847
  id SERIAL PRIMARY KEY,
11
2848
  hash text NOT NULL,
12
2849
  created_at numeric
13
2850
  )
14
- `;await t.run(n);let u=(await t.values(o`SELECT id, hash, created_at FROM ${o.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async f=>{for(let d of e)if(!u||Number(u[2])<d.folderMillis){for(let c of d.sql)await f.run(o.raw(c));await f.run(o`INSERT INTO ${o.identifier(i)} ("hash", "created_at") VALUES(${d.hash}, ${d.folderMillis})`)}})}};var et=class{static[l]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}};var J=class{static[l]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,s;return this.fields?s=this.fields:m(e,O)?s=Object.fromEntries(Object.keys(e._.selectedFields).map(i=>[i,e[i]])):m(e,ne)?s=e[T].selectedFields:m(e,p)?s={}:s=ze(e),new tt({table:e,fields:s,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}},dr=class extends et{static[l]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:s,session:i,dialect:n,withList:a,distinct:u}){super(),this.config={withList:a,table:e,fields:{...t},distinct:u,setOperators:[]},this.isPartialSelect=s,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=Te(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(let f of W(e))this.usedTables.add(f)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,s)=>{let i=this.tableName,n=Te(t);for(let a of W(t))this.usedTables.add(a);if(typeof n=="string"&&this.config.joins?.some(a=>a.alias===n))throw new Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i=="string"&&(this.config.fields={[i]:this.config.fields}),typeof n=="string"&&!m(t,p))){let a=m(t,O)?t._.selectedFields:m(t,I)?t[T].selectedFields:t[h.Symbol.Columns];this.config.fields[n]=a}if(typeof s=="function"&&(s=s(new Proxy(this.config.fields,new P({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:s,table:t,joinType:e,alias:n}),typeof n=="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return s=>{let i=typeof s=="function"?s(Us()):s;if(!Ne(this.getSelectedFields(),i.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:i}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new P({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new P({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new P({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new P({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),s=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=s:this.config.orderBy=s}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...W(this.config.table)),this.config.joins)for(let s of this.config.joins)t.push(...W(s.table));return new Proxy(new O(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new P({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new P({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}},tt=class extends dr{static[l]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=V(this.config.fields),s=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return s.joinsNotNullableMap=this.joinsNotNullableMap,s}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.all()}};Fr(tt,[_]);function rt(r,e){return(t,s,...i)=>{let n=[s,...i].map(a=>({type:r,isAll:e,rightSelect:a}));for(let a of n)if(!Ne(t.getSelectedFields(),a.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return t.addSetOperators(n)}}var Us=()=>({union:Js,unionAll:ks,intersect:Ws,except:Hs}),Js=rt("union",!1),ks=rt("union",!0),Ws=rt("intersect",!1),Hs=rt("except",!1);var be=class{static[l]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=m(e,ce)?e:void 0,this.dialectConfig=m(e,ce)?void 0:e}$with=(e,t)=>{let s=this;return{as:n=>(typeof n=="function"&&(n=n(s)),new Proxy(new pe(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new P({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let t=this;function s(n){return new J({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new J({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:s,selectDistinct:i}}select(e){return new J({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new J({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||(this.dialect=new ge(this.dialectConfig)),this.dialect}};var Be=class{constructor(e,t,s,i){this.table=e,this.session=t,this.dialect=s,this.withList=i}static[l]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");let t=e.map(s=>{let i={},n=this.table[h.Symbol.Columns];for(let a of Object.keys(s)){let u=s[a];i[a]=m(u,p)?u:new R(u,n[a])}return i});return new st(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e=="function"?e(new be):e;if(!m(t,p)&&!Ne(this.table[Ke],t._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new st(this.table,t,this.session,this.dialect,this.withList,!0)}},st=class extends _{constructor(e,t,s,i,n,a){super(),this.session=s,this.dialect=i,this.config={table:e,values:t,withList:n,select:a}}static[l]="SQLiteInsert";config;returning(e=this.config.table[B.Symbol.Columns]){return this.config.returning=V(e),this}onConflictDoNothing(e={}){if(this.config.onConflict||(this.config.onConflict=[]),e.target===void 0)this.config.onConflict.push(o` on conflict do nothing`);else{let t=Array.isArray(e.target)?o`${e.target}`:o`${[e.target]}`,s=e.where?o` where ${e.where}`:o``;this.config.onConflict.push(o` on conflict ${t} do nothing${s}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');this.config.onConflict||(this.config.onConflict=[]);let t=e.where?o` where ${e.where}`:void 0,s=e.targetWhere?o` where ${e.targetWhere}`:void 0,i=e.setWhere?o` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?o`${e.target}`:o`${[e.target]}`,a=this.dialect.buildUpdateSet(this.config.table,Me(this.config.table,e.set));return this.config.onConflict.push(o` on conflict ${n}${s} do update set ${a}${t}${i}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:W(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}};var Ae=class{constructor(e,t,s,i){this.table=e,this.session=t,this.dialect=s,this.withList=i}static[l]="SQLiteUpdateBuilder";set(e){return new pr(this.table,Me(this.table,e),this.session,this.dialect,this.withList)}},pr=class extends _{constructor(e,t,s,i,n){super(),this.session=s,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[l]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,s)=>{let i=Te(t);if(typeof i=="string"&&this.config.joins.some(n=>n.alias===i))throw new Error(`Alias "${i}" is already used in this query`);if(typeof s=="function"){let n=this.config.from?m(t,B)?t[h.Symbol.Columns]:m(t,O)?t._.selectedFields:m(t,ne)?t[T].selectedFields:void 0:void 0;s=s(new Proxy(this.config.table[h.Symbol.Columns],new P({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new P({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:s,table:t,joinType:e,alias:i}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.table[h.Symbol.Columns],new P({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),s=Array.isArray(t)?t:[t];this.config.orderBy=s}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[B.Symbol.Columns]){return this.config.returning=V(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:W(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}};var it=class r extends p{constructor(e){super(r.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.session=e.session,this.sql=r.buildCount(e.source,e.filters)}sql;static[l]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return o`(select count(*) from ${e}${o.raw(" where ").if(t)}${t})`}static buildCount(e,t){return o`select count(*) from ${e}${o.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}};var nt=class{constructor(e,t,s,i,n,a,u,f){this.mode=e,this.fullSchema=t,this.schema=s,this.tableNamesMap=i,this.table=n,this.tableConfig=a,this.dialect=u,this.session=f}static[l]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new ot(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many"):new Pe(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return this.mode==="sync"?new ot(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Pe(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},Pe=class extends _{constructor(e,t,s,i,n,a,u,f,d){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=s,this.table=i,this.tableConfig=n,this.dialect=a,this.session=u,this.config=f,this.mode=d}static[l]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:s}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](s,void 0,this.mode==="first"?"get":"all",!0,(i,n)=>{let a=i.map(u=>We(this.schema,this.tableConfig,u,t.selection,n));return this.mode==="first"?a[0]:a})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){return this.mode==="first"?this._prepare(!1).get():this._prepare(!1).all()}async execute(){return this.executeRaw()}},ot=class extends Pe{static[l]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}};var me=class extends _{constructor(e,t,s,i,n){super(),this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:s}}static[l]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}};var Se=class{constructor(e,t,s,i){this.resultKind=e,this.dialect=t,this.session=s,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[a,u]of Object.entries(this._.schema))n[a]=new nt(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[a],u,t,s);this.$cache={invalidate:async a=>{}}}static[l]="BaseSQLiteDatabase";query;$with=(e,t)=>{let s=this;return{as:n=>(typeof n=="function"&&(n=n(new be(s.dialect))),new Proxy(new pe(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new P({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,t){return new it({source:e,filters:t,session:this.session})}with(...e){let t=this;function s(f){return new J({fields:f??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(f){return new J({fields:f??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(f){return new Ae(f,t.session,t.dialect,e)}function a(f){return new Be(f,t.session,t.dialect,e)}function u(f){return new Oe(f,t.session,t.dialect,e)}return{select:s,selectDistinct:i,update:n,insert:a,delete:u}}select(e){return new J({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new J({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Ae(e,this.session,this.dialect)}$cache;insert(e){return new Be(e,this.session,this.dialect)}delete(e){return new Oe(e,this.session,this.dialect)}run(e){let t=typeof e=="string"?o.raw(e):e.getSQL();return this.resultKind==="async"?new me(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session)):this.session.run(t)}all(e){let t=typeof e=="string"?o.raw(e):e.getSQL();return this.resultKind==="async"?new me(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session)):this.session.all(t)}get(e){let t=typeof e=="string"?o.raw(e):e.getSQL();return this.resultKind==="async"?new me(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session)):this.session.get(t)}values(e){let t=typeof e=="string"?o.raw(e):e.getSQL();return this.resultKind==="async"?new me(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session)):this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}};var yr=class{static[l]="Cache"},at=class extends yr{strategy(){return"all"}static[l]="NoopCache";async get(e){}async put(e,t,s,i){}async onMutate(e){}};async function gr(r,e){let t=`${r}-${JSON.stringify(e)}`,i=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",i);return[...new Uint8Array(n)].map(f=>f.toString(16).padStart(2,"0")).join("")}var br=class extends _{constructor(e){super(),this.resultCb=e}static[l]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}},lt=class{constructor(e,t,s,i,n,a){this.mode=e,this.executeMethod=t,this.query=s,this.cache=i,this.queryMetadata=n,this.cacheConfig=a,i&&i.strategy()==="all"&&a===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}static[l]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,s){if(this.cache===void 0||m(this.cache,at)||this.queryMetadata===void 0)try{return await s()}catch(i){throw new re(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await s()}catch(i){throw new re(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([s(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new re(e,t,i)}if(!this.cacheConfig)try{return await s()}catch(i){throw new re(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await gr(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await s()}catch(a){throw new re(e,t,a)}return await this.cache.put(this.cacheConfig.tag??await gr(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await s()}catch(i){throw new re(e,t,i)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw new Error("Not implemented")}mapGetResult(e,t){throw new Error("Not implemented")}execute(e){return this.mode==="async"?this[this.executeMethod](e):new br(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}},ut=class{constructor(e){this.dialect=e}static[l]="SQLiteSession";prepareOneTimeQuery(e,t,s,i,n,a,u){return this.prepareQuery(e,t,s,i,n,a,u)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(s){throw new ue({cause:s,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw new Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw new Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw new Error("Not implemented")}},ct=class extends Se{constructor(e,t,s,i,n=0){super(e,t,s,i),this.schema=i,this.nestedIndex=n}static[l]="SQLiteTransaction";rollback(){throw new Xe}};var mt=class extends ut{constructor(e,t,s,i={}){super(t),this.client=e,this.schema=s,this.logger=i.logger??new De}static[l]="SQLiteDOSession";logger;prepareQuery(e,t,s,i,n){return new wr(this.client,e,this.logger,t,s,i,n)}transaction(e,t){let s=new Sr("sync",this.dialect,this,this.schema);return this.client.transactionSync(()=>{e(s)}),{}}},Sr=class r extends ct{static[l]="SQLiteDOTransaction";transaction(e){let t=new r("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);return this.session.transaction(()=>e(t)),{}}},wr=class extends lt{constructor(e,t,s,i,n,a,u){super("sync",n,t,void 0,void 0,void 0),this.client=e,this.logger=s,this.fields=i,this._isResponseInArrayMode=a,this.customResultMapper=u}static[l]="SQLiteDOPreparedQuery";run(e){let t=Ce(this.query.params,e??{});this.logger.logQuery(this.query.sql,t),t.length>0?this.client.sql.exec(this.query.sql,...t):this.client.sql.exec(this.query.sql)}all(e){let{fields:t,joinsNotNullableMap:s,query:i,logger:n,client:a,customResultMapper:u}=this;if(!t&&!u){let d=Ce(i.params,e??{});return n.logQuery(i.sql,d),d.length>0?a.sql.exec(i.sql,...d).toArray():a.sql.exec(i.sql).toArray()}let f=this.values(e);return u?u(f):f.map(d=>Bt(t,d,s))}get(e){let t=Ce(this.query.params,e??{});this.logger.logQuery(this.query.sql,t);let{fields:s,client:i,joinsNotNullableMap:n,customResultMapper:a,query:u}=this;if(!s&&!a)return(t.length>0?i.sql.exec(u.sql,...t):i.sql.exec(u.sql)).next().value;let f=this.values(e),d=f[0];if(d)return a?a(f):Bt(s,d,n)}values(e){let t=Ce(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),(t.length>0?this.client.sql.exec(this.query.sql,...t):this.client.sql.exec(this.query.sql)).raw().toArray()}isResponseInArrayMode(){return this._isResponseInArrayMode}};var xr=class extends Se{static[l]="DrizzleSqliteDODatabase"};function Ts(r,e={}){let t=new ge({casing:e.casing}),s;e.logger===!0?s=new _e:e.logger!==!1&&(s=e.logger);let i;if(e.schema){let u=ms(e.schema,hs);i={fullSchema:e.schema,schema:u.tables,tableNamesMap:u.tableNamesMap}}let n=new mt(r,t,i,{logger:s}),a=new xr("sync",t,n,i);return a.$client=r,a}function Ys({journal:r,migrations:e}){let t=[];for(let s of r.entries){let i=e[`m${s.idx.toString().padStart(4,"0")}`];if(!i)throw new Error(`Missing migration: ${s.tag}`);try{let n=i.split("--> statement-breakpoint").map(a=>a);t.push({sql:n,bps:s.breakpoints,folderMillis:s.when,hash:""})}catch{throw new Error(`Failed to parse migration: ${s.tag}`)}}return t}async function $s(r,e){let t=Ys(e);r.transaction(s=>{try{let i="__drizzle_migrations",n=o`
15
- CREATE TABLE IF NOT EXISTS ${o.identifier(i)} (
2851
+ `;
2852
+ await session.run(migrationTableCreate);
2853
+ const lastDbMigration = (await session.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`))[0] ?? void 0;
2854
+ await session.transaction(async (tx) => {
2855
+ for (const migration of migrations) if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
2856
+ for (const stmt of migration.sql) await tx.run(sql.raw(stmt));
2857
+ await tx.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
2858
+ }
2859
+ });
2860
+ }
2861
+ };
2862
+
2863
+ //#endregion
2864
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/query-builders/query-builder.js
2865
+ var TypedQueryBuilder = class {
2866
+ static [entityKind] = "TypedQueryBuilder";
2867
+ /** @internal */
2868
+ getSelectedFields() {
2869
+ return this._.selectedFields;
2870
+ }
2871
+ };
2872
+
2873
+ //#endregion
2874
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/query-builders/select.js
2875
+ var SQLiteSelectBuilder = class {
2876
+ static [entityKind] = "SQLiteSelectBuilder";
2877
+ fields;
2878
+ session;
2879
+ dialect;
2880
+ withList;
2881
+ distinct;
2882
+ constructor(config) {
2883
+ this.fields = config.fields;
2884
+ this.session = config.session;
2885
+ this.dialect = config.dialect;
2886
+ this.withList = config.withList;
2887
+ this.distinct = config.distinct;
2888
+ }
2889
+ from(source) {
2890
+ const isPartialSelect = !!this.fields;
2891
+ let fields;
2892
+ if (this.fields) fields = this.fields;
2893
+ else if (is(source, Subquery)) fields = Object.fromEntries(Object.keys(source._.selectedFields).map((key) => [key, source[key]]));
2894
+ else if (is(source, SQLiteViewBase)) fields = source[ViewBaseConfig].selectedFields;
2895
+ else if (is(source, SQL)) fields = {};
2896
+ else fields = getTableColumns(source);
2897
+ return new SQLiteSelectBase({
2898
+ table: source,
2899
+ fields,
2900
+ isPartialSelect,
2901
+ session: this.session,
2902
+ dialect: this.dialect,
2903
+ withList: this.withList,
2904
+ distinct: this.distinct
2905
+ });
2906
+ }
2907
+ };
2908
+ var SQLiteSelectQueryBuilderBase = class extends TypedQueryBuilder {
2909
+ static [entityKind] = "SQLiteSelectQueryBuilder";
2910
+ _;
2911
+ /** @internal */
2912
+ config;
2913
+ joinsNotNullableMap;
2914
+ tableName;
2915
+ isPartialSelect;
2916
+ session;
2917
+ dialect;
2918
+ cacheConfig = void 0;
2919
+ usedTables = /* @__PURE__ */ new Set();
2920
+ constructor({ table, fields, isPartialSelect, session, dialect: dialect$1, withList, distinct }) {
2921
+ super();
2922
+ this.config = {
2923
+ withList,
2924
+ table,
2925
+ fields: { ...fields },
2926
+ distinct,
2927
+ setOperators: []
2928
+ };
2929
+ this.isPartialSelect = isPartialSelect;
2930
+ this.session = session;
2931
+ this.dialect = dialect$1;
2932
+ this._ = {
2933
+ selectedFields: fields,
2934
+ config: this.config
2935
+ };
2936
+ this.tableName = getTableLikeName(table);
2937
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
2938
+ for (const item of extractUsedTable(table)) this.usedTables.add(item);
2939
+ }
2940
+ /** @internal */
2941
+ getUsedTables() {
2942
+ return [...this.usedTables];
2943
+ }
2944
+ createJoin(joinType) {
2945
+ return (table, on) => {
2946
+ const baseTableName = this.tableName;
2947
+ const tableName = getTableLikeName(table);
2948
+ for (const item of extractUsedTable(table)) this.usedTables.add(item);
2949
+ if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
2950
+ if (!this.isPartialSelect) {
2951
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
2952
+ if (typeof tableName === "string" && !is(table, SQL)) {
2953
+ const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
2954
+ this.config.fields[tableName] = selection;
2955
+ }
2956
+ }
2957
+ if (typeof on === "function") on = on(new Proxy(this.config.fields, new SelectionProxyHandler({
2958
+ sqlAliasedBehavior: "sql",
2959
+ sqlBehavior: "sql"
2960
+ })));
2961
+ if (!this.config.joins) this.config.joins = [];
2962
+ this.config.joins.push({
2963
+ on,
2964
+ table,
2965
+ joinType,
2966
+ alias: tableName
2967
+ });
2968
+ if (typeof tableName === "string") switch (joinType) {
2969
+ case "left":
2970
+ this.joinsNotNullableMap[tableName] = false;
2971
+ break;
2972
+ case "right":
2973
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
2974
+ this.joinsNotNullableMap[tableName] = true;
2975
+ break;
2976
+ case "cross":
2977
+ case "inner":
2978
+ this.joinsNotNullableMap[tableName] = true;
2979
+ break;
2980
+ case "full":
2981
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
2982
+ this.joinsNotNullableMap[tableName] = false;
2983
+ break;
2984
+ }
2985
+ return this;
2986
+ };
2987
+ }
2988
+ /**
2989
+ * Executes a `left join` operation by adding another table to the current query.
2990
+ *
2991
+ * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
2992
+ *
2993
+ * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
2994
+ *
2995
+ * @param table the table to join.
2996
+ * @param on the `on` clause.
2997
+ *
2998
+ * @example
2999
+ *
3000
+ * ```ts
3001
+ * // Select all users and their pets
3002
+ * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
3003
+ * .from(users)
3004
+ * .leftJoin(pets, eq(users.id, pets.ownerId))
3005
+ *
3006
+ * // Select userId and petId
3007
+ * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
3008
+ * userId: users.id,
3009
+ * petId: pets.id,
3010
+ * })
3011
+ * .from(users)
3012
+ * .leftJoin(pets, eq(users.id, pets.ownerId))
3013
+ * ```
3014
+ */
3015
+ leftJoin = this.createJoin("left");
3016
+ /**
3017
+ * Executes a `right join` operation by adding another table to the current query.
3018
+ *
3019
+ * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
3020
+ *
3021
+ * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
3022
+ *
3023
+ * @param table the table to join.
3024
+ * @param on the `on` clause.
3025
+ *
3026
+ * @example
3027
+ *
3028
+ * ```ts
3029
+ * // Select all users and their pets
3030
+ * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
3031
+ * .from(users)
3032
+ * .rightJoin(pets, eq(users.id, pets.ownerId))
3033
+ *
3034
+ * // Select userId and petId
3035
+ * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
3036
+ * userId: users.id,
3037
+ * petId: pets.id,
3038
+ * })
3039
+ * .from(users)
3040
+ * .rightJoin(pets, eq(users.id, pets.ownerId))
3041
+ * ```
3042
+ */
3043
+ rightJoin = this.createJoin("right");
3044
+ /**
3045
+ * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
3046
+ *
3047
+ * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
3048
+ *
3049
+ * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
3050
+ *
3051
+ * @param table the table to join.
3052
+ * @param on the `on` clause.
3053
+ *
3054
+ * @example
3055
+ *
3056
+ * ```ts
3057
+ * // Select all users and their pets
3058
+ * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
3059
+ * .from(users)
3060
+ * .innerJoin(pets, eq(users.id, pets.ownerId))
3061
+ *
3062
+ * // Select userId and petId
3063
+ * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
3064
+ * userId: users.id,
3065
+ * petId: pets.id,
3066
+ * })
3067
+ * .from(users)
3068
+ * .innerJoin(pets, eq(users.id, pets.ownerId))
3069
+ * ```
3070
+ */
3071
+ innerJoin = this.createJoin("inner");
3072
+ /**
3073
+ * Executes a `full join` operation by combining rows from two tables into a new table.
3074
+ *
3075
+ * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
3076
+ *
3077
+ * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
3078
+ *
3079
+ * @param table the table to join.
3080
+ * @param on the `on` clause.
3081
+ *
3082
+ * @example
3083
+ *
3084
+ * ```ts
3085
+ * // Select all users and their pets
3086
+ * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
3087
+ * .from(users)
3088
+ * .fullJoin(pets, eq(users.id, pets.ownerId))
3089
+ *
3090
+ * // Select userId and petId
3091
+ * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
3092
+ * userId: users.id,
3093
+ * petId: pets.id,
3094
+ * })
3095
+ * .from(users)
3096
+ * .fullJoin(pets, eq(users.id, pets.ownerId))
3097
+ * ```
3098
+ */
3099
+ fullJoin = this.createJoin("full");
3100
+ /**
3101
+ * Executes a `cross join` operation by combining rows from two tables into a new table.
3102
+ *
3103
+ * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
3104
+ *
3105
+ * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
3106
+ *
3107
+ * @param table the table to join.
3108
+ *
3109
+ * @example
3110
+ *
3111
+ * ```ts
3112
+ * // Select all users, each user with every pet
3113
+ * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
3114
+ * .from(users)
3115
+ * .crossJoin(pets)
3116
+ *
3117
+ * // Select userId and petId
3118
+ * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
3119
+ * userId: users.id,
3120
+ * petId: pets.id,
3121
+ * })
3122
+ * .from(users)
3123
+ * .crossJoin(pets)
3124
+ * ```
3125
+ */
3126
+ crossJoin = this.createJoin("cross");
3127
+ createSetOperator(type, isAll) {
3128
+ return (rightSelection) => {
3129
+ const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
3130
+ if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
3131
+ this.config.setOperators.push({
3132
+ type,
3133
+ isAll,
3134
+ rightSelect
3135
+ });
3136
+ return this;
3137
+ };
3138
+ }
3139
+ /**
3140
+ * Adds `union` set operator to the query.
3141
+ *
3142
+ * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
3143
+ *
3144
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
3145
+ *
3146
+ * @example
3147
+ *
3148
+ * ```ts
3149
+ * // Select all unique names from customers and users tables
3150
+ * await db.select({ name: users.name })
3151
+ * .from(users)
3152
+ * .union(
3153
+ * db.select({ name: customers.name }).from(customers)
3154
+ * );
3155
+ * // or
3156
+ * import { union } from 'drizzle-orm/sqlite-core'
3157
+ *
3158
+ * await union(
3159
+ * db.select({ name: users.name }).from(users),
3160
+ * db.select({ name: customers.name }).from(customers)
3161
+ * );
3162
+ * ```
3163
+ */
3164
+ union = this.createSetOperator("union", false);
3165
+ /**
3166
+ * Adds `union all` set operator to the query.
3167
+ *
3168
+ * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
3169
+ *
3170
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
3171
+ *
3172
+ * @example
3173
+ *
3174
+ * ```ts
3175
+ * // Select all transaction ids from both online and in-store sales
3176
+ * await db.select({ transaction: onlineSales.transactionId })
3177
+ * .from(onlineSales)
3178
+ * .unionAll(
3179
+ * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
3180
+ * );
3181
+ * // or
3182
+ * import { unionAll } from 'drizzle-orm/sqlite-core'
3183
+ *
3184
+ * await unionAll(
3185
+ * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
3186
+ * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
3187
+ * );
3188
+ * ```
3189
+ */
3190
+ unionAll = this.createSetOperator("union", true);
3191
+ /**
3192
+ * Adds `intersect` set operator to the query.
3193
+ *
3194
+ * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
3195
+ *
3196
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
3197
+ *
3198
+ * @example
3199
+ *
3200
+ * ```ts
3201
+ * // Select course names that are offered in both departments A and B
3202
+ * await db.select({ courseName: depA.courseName })
3203
+ * .from(depA)
3204
+ * .intersect(
3205
+ * db.select({ courseName: depB.courseName }).from(depB)
3206
+ * );
3207
+ * // or
3208
+ * import { intersect } from 'drizzle-orm/sqlite-core'
3209
+ *
3210
+ * await intersect(
3211
+ * db.select({ courseName: depA.courseName }).from(depA),
3212
+ * db.select({ courseName: depB.courseName }).from(depB)
3213
+ * );
3214
+ * ```
3215
+ */
3216
+ intersect = this.createSetOperator("intersect", false);
3217
+ /**
3218
+ * Adds `except` set operator to the query.
3219
+ *
3220
+ * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
3221
+ *
3222
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
3223
+ *
3224
+ * @example
3225
+ *
3226
+ * ```ts
3227
+ * // Select all courses offered in department A but not in department B
3228
+ * await db.select({ courseName: depA.courseName })
3229
+ * .from(depA)
3230
+ * .except(
3231
+ * db.select({ courseName: depB.courseName }).from(depB)
3232
+ * );
3233
+ * // or
3234
+ * import { except } from 'drizzle-orm/sqlite-core'
3235
+ *
3236
+ * await except(
3237
+ * db.select({ courseName: depA.courseName }).from(depA),
3238
+ * db.select({ courseName: depB.courseName }).from(depB)
3239
+ * );
3240
+ * ```
3241
+ */
3242
+ except = this.createSetOperator("except", false);
3243
+ /** @internal */
3244
+ addSetOperators(setOperators) {
3245
+ this.config.setOperators.push(...setOperators);
3246
+ return this;
3247
+ }
3248
+ /**
3249
+ * Adds a `where` clause to the query.
3250
+ *
3251
+ * Calling this method will select only those rows that fulfill a specified condition.
3252
+ *
3253
+ * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
3254
+ *
3255
+ * @param where the `where` clause.
3256
+ *
3257
+ * @example
3258
+ * You can use conditional operators and `sql function` to filter the rows to be selected.
3259
+ *
3260
+ * ```ts
3261
+ * // Select all cars with green color
3262
+ * await db.select().from(cars).where(eq(cars.color, 'green'));
3263
+ * // or
3264
+ * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
3265
+ * ```
3266
+ *
3267
+ * You can logically combine conditional operators with `and()` and `or()` operators:
3268
+ *
3269
+ * ```ts
3270
+ * // Select all BMW cars with a green color
3271
+ * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
3272
+ *
3273
+ * // Select all cars with the green or blue color
3274
+ * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
3275
+ * ```
3276
+ */
3277
+ where(where) {
3278
+ if (typeof where === "function") where = where(new Proxy(this.config.fields, new SelectionProxyHandler({
3279
+ sqlAliasedBehavior: "sql",
3280
+ sqlBehavior: "sql"
3281
+ })));
3282
+ this.config.where = where;
3283
+ return this;
3284
+ }
3285
+ /**
3286
+ * Adds a `having` clause to the query.
3287
+ *
3288
+ * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
3289
+ *
3290
+ * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
3291
+ *
3292
+ * @param having the `having` clause.
3293
+ *
3294
+ * @example
3295
+ *
3296
+ * ```ts
3297
+ * // Select all brands with more than one car
3298
+ * await db.select({
3299
+ * brand: cars.brand,
3300
+ * count: sql<number>`cast(count(${cars.id}) as int)`,
3301
+ * })
3302
+ * .from(cars)
3303
+ * .groupBy(cars.brand)
3304
+ * .having(({ count }) => gt(count, 1));
3305
+ * ```
3306
+ */
3307
+ having(having) {
3308
+ if (typeof having === "function") having = having(new Proxy(this.config.fields, new SelectionProxyHandler({
3309
+ sqlAliasedBehavior: "sql",
3310
+ sqlBehavior: "sql"
3311
+ })));
3312
+ this.config.having = having;
3313
+ return this;
3314
+ }
3315
+ groupBy(...columns$1) {
3316
+ if (typeof columns$1[0] === "function") {
3317
+ const groupBy = columns$1[0](new Proxy(this.config.fields, new SelectionProxyHandler({
3318
+ sqlAliasedBehavior: "alias",
3319
+ sqlBehavior: "sql"
3320
+ })));
3321
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
3322
+ } else this.config.groupBy = columns$1;
3323
+ return this;
3324
+ }
3325
+ orderBy(...columns$1) {
3326
+ if (typeof columns$1[0] === "function") {
3327
+ const orderBy = columns$1[0](new Proxy(this.config.fields, new SelectionProxyHandler({
3328
+ sqlAliasedBehavior: "alias",
3329
+ sqlBehavior: "sql"
3330
+ })));
3331
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
3332
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;
3333
+ else this.config.orderBy = orderByArray;
3334
+ } else {
3335
+ const orderByArray = columns$1;
3336
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;
3337
+ else this.config.orderBy = orderByArray;
3338
+ }
3339
+ return this;
3340
+ }
3341
+ /**
3342
+ * Adds a `limit` clause to the query.
3343
+ *
3344
+ * Calling this method will set the maximum number of rows that will be returned by this query.
3345
+ *
3346
+ * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
3347
+ *
3348
+ * @param limit the `limit` clause.
3349
+ *
3350
+ * @example
3351
+ *
3352
+ * ```ts
3353
+ * // Get the first 10 people from this query.
3354
+ * await db.select().from(people).limit(10);
3355
+ * ```
3356
+ */
3357
+ limit(limit) {
3358
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).limit = limit;
3359
+ else this.config.limit = limit;
3360
+ return this;
3361
+ }
3362
+ /**
3363
+ * Adds an `offset` clause to the query.
3364
+ *
3365
+ * Calling this method will skip a number of rows when returning results from this query.
3366
+ *
3367
+ * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
3368
+ *
3369
+ * @param offset the `offset` clause.
3370
+ *
3371
+ * @example
3372
+ *
3373
+ * ```ts
3374
+ * // Get the 10th-20th people from this query.
3375
+ * await db.select().from(people).offset(10).limit(10);
3376
+ * ```
3377
+ */
3378
+ offset(offset) {
3379
+ if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).offset = offset;
3380
+ else this.config.offset = offset;
3381
+ return this;
3382
+ }
3383
+ /** @internal */
3384
+ getSQL() {
3385
+ return this.dialect.buildSelectQuery(this.config);
3386
+ }
3387
+ toSQL() {
3388
+ const { typings: _typings,...rest } = this.dialect.sqlToQuery(this.getSQL());
3389
+ return rest;
3390
+ }
3391
+ as(alias) {
3392
+ const usedTables = [];
3393
+ usedTables.push(...extractUsedTable(this.config.table));
3394
+ if (this.config.joins) for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
3395
+ return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), new SelectionProxyHandler({
3396
+ alias,
3397
+ sqlAliasedBehavior: "alias",
3398
+ sqlBehavior: "error"
3399
+ }));
3400
+ }
3401
+ /** @internal */
3402
+ getSelectedFields() {
3403
+ return new Proxy(this.config.fields, new SelectionProxyHandler({
3404
+ alias: this.tableName,
3405
+ sqlAliasedBehavior: "alias",
3406
+ sqlBehavior: "error"
3407
+ }));
3408
+ }
3409
+ $dynamic() {
3410
+ return this;
3411
+ }
3412
+ };
3413
+ var SQLiteSelectBase = class extends SQLiteSelectQueryBuilderBase {
3414
+ static [entityKind] = "SQLiteSelect";
3415
+ /** @internal */
3416
+ _prepare(isOneTimeQuery = true) {
3417
+ if (!this.session) throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
3418
+ const fieldsList = orderSelectedFields(this.config.fields);
3419
+ const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), fieldsList, "all", true, void 0, {
3420
+ type: "select",
3421
+ tables: [...this.usedTables]
3422
+ }, this.cacheConfig);
3423
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
3424
+ return query;
3425
+ }
3426
+ $withCache(config) {
3427
+ this.cacheConfig = config === void 0 ? {
3428
+ config: {},
3429
+ enable: true,
3430
+ autoInvalidate: true
3431
+ } : config === false ? { enable: false } : {
3432
+ enable: true,
3433
+ autoInvalidate: true,
3434
+ ...config
3435
+ };
3436
+ return this;
3437
+ }
3438
+ prepare() {
3439
+ return this._prepare(false);
3440
+ }
3441
+ run = (placeholderValues) => {
3442
+ return this._prepare().run(placeholderValues);
3443
+ };
3444
+ all = (placeholderValues) => {
3445
+ return this._prepare().all(placeholderValues);
3446
+ };
3447
+ get = (placeholderValues) => {
3448
+ return this._prepare().get(placeholderValues);
3449
+ };
3450
+ values = (placeholderValues) => {
3451
+ return this._prepare().values(placeholderValues);
3452
+ };
3453
+ async execute() {
3454
+ return this.all();
3455
+ }
3456
+ };
3457
+ applyMixins(SQLiteSelectBase, [QueryPromise]);
3458
+ function createSetOperator(type, isAll) {
3459
+ return (leftSelect, rightSelect, ...restSelects) => {
3460
+ const setOperators = [rightSelect, ...restSelects].map((select) => ({
3461
+ type,
3462
+ isAll,
3463
+ rightSelect: select
3464
+ }));
3465
+ for (const setOperator of setOperators) if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
3466
+ return leftSelect.addSetOperators(setOperators);
3467
+ };
3468
+ }
3469
+ const getSQLiteSetOperators = () => ({
3470
+ union,
3471
+ unionAll,
3472
+ intersect,
3473
+ except
3474
+ });
3475
+ const union = createSetOperator("union", false);
3476
+ const unionAll = createSetOperator("union", true);
3477
+ const intersect = createSetOperator("intersect", false);
3478
+ const except = createSetOperator("except", false);
3479
+
3480
+ //#endregion
3481
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js
3482
+ var QueryBuilder = class {
3483
+ static [entityKind] = "SQLiteQueryBuilder";
3484
+ dialect;
3485
+ dialectConfig;
3486
+ constructor(dialect$1) {
3487
+ this.dialect = is(dialect$1, SQLiteDialect) ? dialect$1 : void 0;
3488
+ this.dialectConfig = is(dialect$1, SQLiteDialect) ? void 0 : dialect$1;
3489
+ }
3490
+ $with = (alias, selection) => {
3491
+ const queryBuilder = this;
3492
+ const as = (qb) => {
3493
+ if (typeof qb === "function") qb = qb(queryBuilder);
3494
+ return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({
3495
+ alias,
3496
+ sqlAliasedBehavior: "alias",
3497
+ sqlBehavior: "error"
3498
+ }));
3499
+ };
3500
+ return { as };
3501
+ };
3502
+ with(...queries) {
3503
+ const self = this;
3504
+ function select(fields) {
3505
+ return new SQLiteSelectBuilder({
3506
+ fields: fields ?? void 0,
3507
+ session: void 0,
3508
+ dialect: self.getDialect(),
3509
+ withList: queries
3510
+ });
3511
+ }
3512
+ function selectDistinct(fields) {
3513
+ return new SQLiteSelectBuilder({
3514
+ fields: fields ?? void 0,
3515
+ session: void 0,
3516
+ dialect: self.getDialect(),
3517
+ withList: queries,
3518
+ distinct: true
3519
+ });
3520
+ }
3521
+ return {
3522
+ select,
3523
+ selectDistinct
3524
+ };
3525
+ }
3526
+ select(fields) {
3527
+ return new SQLiteSelectBuilder({
3528
+ fields: fields ?? void 0,
3529
+ session: void 0,
3530
+ dialect: this.getDialect()
3531
+ });
3532
+ }
3533
+ selectDistinct(fields) {
3534
+ return new SQLiteSelectBuilder({
3535
+ fields: fields ?? void 0,
3536
+ session: void 0,
3537
+ dialect: this.getDialect(),
3538
+ distinct: true
3539
+ });
3540
+ }
3541
+ getDialect() {
3542
+ if (!this.dialect) this.dialect = new SQLiteSyncDialect(this.dialectConfig);
3543
+ return this.dialect;
3544
+ }
3545
+ };
3546
+
3547
+ //#endregion
3548
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js
3549
+ var SQLiteInsertBuilder = class {
3550
+ constructor(table, session, dialect$1, withList) {
3551
+ this.table = table;
3552
+ this.session = session;
3553
+ this.dialect = dialect$1;
3554
+ this.withList = withList;
3555
+ }
3556
+ static [entityKind] = "SQLiteInsertBuilder";
3557
+ values(values) {
3558
+ values = Array.isArray(values) ? values : [values];
3559
+ if (values.length === 0) throw new Error("values() must be called with at least one value");
3560
+ const mappedValues = values.map((entry) => {
3561
+ const result = {};
3562
+ const cols = this.table[Table.Symbol.Columns];
3563
+ for (const colKey of Object.keys(entry)) {
3564
+ const colValue = entry[colKey];
3565
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
3566
+ }
3567
+ return result;
3568
+ });
3569
+ return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
3570
+ }
3571
+ select(selectQuery) {
3572
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
3573
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");
3574
+ return new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
3575
+ }
3576
+ };
3577
+ var SQLiteInsertBase = class extends QueryPromise {
3578
+ constructor(table, values, session, dialect$1, withList, select) {
3579
+ super();
3580
+ this.session = session;
3581
+ this.dialect = dialect$1;
3582
+ this.config = {
3583
+ table,
3584
+ values,
3585
+ withList,
3586
+ select
3587
+ };
3588
+ }
3589
+ static [entityKind] = "SQLiteInsert";
3590
+ /** @internal */
3591
+ config;
3592
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
3593
+ this.config.returning = orderSelectedFields(fields);
3594
+ return this;
3595
+ }
3596
+ /**
3597
+ * Adds an `on conflict do nothing` clause to the query.
3598
+ *
3599
+ * Calling this method simply avoids inserting a row as its alternative action.
3600
+ *
3601
+ * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
3602
+ *
3603
+ * @param config The `target` and `where` clauses.
3604
+ *
3605
+ * @example
3606
+ * ```ts
3607
+ * // Insert one row and cancel the insert if there's a conflict
3608
+ * await db.insert(cars)
3609
+ * .values({ id: 1, brand: 'BMW' })
3610
+ * .onConflictDoNothing();
3611
+ *
3612
+ * // Explicitly specify conflict target
3613
+ * await db.insert(cars)
3614
+ * .values({ id: 1, brand: 'BMW' })
3615
+ * .onConflictDoNothing({ target: cars.id });
3616
+ * ```
3617
+ */
3618
+ onConflictDoNothing(config = {}) {
3619
+ if (!this.config.onConflict) this.config.onConflict = [];
3620
+ if (config.target === void 0) this.config.onConflict.push(sql` on conflict do nothing`);
3621
+ else {
3622
+ const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
3623
+ const whereSql = config.where ? sql` where ${config.where}` : sql``;
3624
+ this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);
3625
+ }
3626
+ return this;
3627
+ }
3628
+ /**
3629
+ * Adds an `on conflict do update` clause to the query.
3630
+ *
3631
+ * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
3632
+ *
3633
+ * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
3634
+ *
3635
+ * @param config The `target`, `set` and `where` clauses.
3636
+ *
3637
+ * @example
3638
+ * ```ts
3639
+ * // Update the row if there's a conflict
3640
+ * await db.insert(cars)
3641
+ * .values({ id: 1, brand: 'BMW' })
3642
+ * .onConflictDoUpdate({
3643
+ * target: cars.id,
3644
+ * set: { brand: 'Porsche' }
3645
+ * });
3646
+ *
3647
+ * // Upsert with 'where' clause
3648
+ * await db.insert(cars)
3649
+ * .values({ id: 1, brand: 'BMW' })
3650
+ * .onConflictDoUpdate({
3651
+ * target: cars.id,
3652
+ * set: { brand: 'newBMW' },
3653
+ * where: sql`${cars.createdAt} > '2023-01-01'::date`,
3654
+ * });
3655
+ * ```
3656
+ */
3657
+ onConflictDoUpdate(config) {
3658
+ if (config.where && (config.targetWhere || config.setWhere)) throw new Error("You cannot use both \"where\" and \"targetWhere\"/\"setWhere\" at the same time - \"where\" is deprecated, use \"targetWhere\" or \"setWhere\" instead.");
3659
+ if (!this.config.onConflict) this.config.onConflict = [];
3660
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
3661
+ const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
3662
+ const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
3663
+ const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
3664
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
3665
+ this.config.onConflict.push(sql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`);
3666
+ return this;
3667
+ }
3668
+ /** @internal */
3669
+ getSQL() {
3670
+ return this.dialect.buildInsertQuery(this.config);
3671
+ }
3672
+ toSQL() {
3673
+ const { typings: _typings,...rest } = this.dialect.sqlToQuery(this.getSQL());
3674
+ return rest;
3675
+ }
3676
+ /** @internal */
3677
+ _prepare(isOneTimeQuery = true) {
3678
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, void 0, {
3679
+ type: "insert",
3680
+ tables: extractUsedTable(this.config.table)
3681
+ });
3682
+ }
3683
+ prepare() {
3684
+ return this._prepare(false);
3685
+ }
3686
+ run = (placeholderValues) => {
3687
+ return this._prepare().run(placeholderValues);
3688
+ };
3689
+ all = (placeholderValues) => {
3690
+ return this._prepare().all(placeholderValues);
3691
+ };
3692
+ get = (placeholderValues) => {
3693
+ return this._prepare().get(placeholderValues);
3694
+ };
3695
+ values = (placeholderValues) => {
3696
+ return this._prepare().values(placeholderValues);
3697
+ };
3698
+ async execute() {
3699
+ return this.config.returning ? this.all() : this.run();
3700
+ }
3701
+ $dynamic() {
3702
+ return this;
3703
+ }
3704
+ };
3705
+
3706
+ //#endregion
3707
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/query-builders/update.js
3708
+ var SQLiteUpdateBuilder = class {
3709
+ constructor(table, session, dialect$1, withList) {
3710
+ this.table = table;
3711
+ this.session = session;
3712
+ this.dialect = dialect$1;
3713
+ this.withList = withList;
3714
+ }
3715
+ static [entityKind] = "SQLiteUpdateBuilder";
3716
+ set(values) {
3717
+ return new SQLiteUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);
3718
+ }
3719
+ };
3720
+ var SQLiteUpdateBase = class extends QueryPromise {
3721
+ constructor(table, set, session, dialect$1, withList) {
3722
+ super();
3723
+ this.session = session;
3724
+ this.dialect = dialect$1;
3725
+ this.config = {
3726
+ set,
3727
+ table,
3728
+ withList,
3729
+ joins: []
3730
+ };
3731
+ }
3732
+ static [entityKind] = "SQLiteUpdate";
3733
+ /** @internal */
3734
+ config;
3735
+ from(source) {
3736
+ this.config.from = source;
3737
+ return this;
3738
+ }
3739
+ createJoin(joinType) {
3740
+ return (table, on) => {
3741
+ const tableName = getTableLikeName(table);
3742
+ if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
3743
+ if (typeof on === "function") {
3744
+ const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0;
3745
+ on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
3746
+ sqlAliasedBehavior: "sql",
3747
+ sqlBehavior: "sql"
3748
+ })), from && new Proxy(from, new SelectionProxyHandler({
3749
+ sqlAliasedBehavior: "sql",
3750
+ sqlBehavior: "sql"
3751
+ })));
3752
+ }
3753
+ this.config.joins.push({
3754
+ on,
3755
+ table,
3756
+ joinType,
3757
+ alias: tableName
3758
+ });
3759
+ return this;
3760
+ };
3761
+ }
3762
+ leftJoin = this.createJoin("left");
3763
+ rightJoin = this.createJoin("right");
3764
+ innerJoin = this.createJoin("inner");
3765
+ fullJoin = this.createJoin("full");
3766
+ /**
3767
+ * Adds a 'where' clause to the query.
3768
+ *
3769
+ * Calling this method will update only those rows that fulfill a specified condition.
3770
+ *
3771
+ * See docs: {@link https://orm.drizzle.team/docs/update}
3772
+ *
3773
+ * @param where the 'where' clause.
3774
+ *
3775
+ * @example
3776
+ * You can use conditional operators and `sql function` to filter the rows to be updated.
3777
+ *
3778
+ * ```ts
3779
+ * // Update all cars with green color
3780
+ * db.update(cars).set({ color: 'red' })
3781
+ * .where(eq(cars.color, 'green'));
3782
+ * // or
3783
+ * db.update(cars).set({ color: 'red' })
3784
+ * .where(sql`${cars.color} = 'green'`)
3785
+ * ```
3786
+ *
3787
+ * You can logically combine conditional operators with `and()` and `or()` operators:
3788
+ *
3789
+ * ```ts
3790
+ * // Update all BMW cars with a green color
3791
+ * db.update(cars).set({ color: 'red' })
3792
+ * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
3793
+ *
3794
+ * // Update all cars with the green or blue color
3795
+ * db.update(cars).set({ color: 'red' })
3796
+ * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
3797
+ * ```
3798
+ */
3799
+ where(where) {
3800
+ this.config.where = where;
3801
+ return this;
3802
+ }
3803
+ orderBy(...columns$1) {
3804
+ if (typeof columns$1[0] === "function") {
3805
+ const orderBy = columns$1[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
3806
+ sqlAliasedBehavior: "alias",
3807
+ sqlBehavior: "sql"
3808
+ })));
3809
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
3810
+ this.config.orderBy = orderByArray;
3811
+ } else {
3812
+ const orderByArray = columns$1;
3813
+ this.config.orderBy = orderByArray;
3814
+ }
3815
+ return this;
3816
+ }
3817
+ limit(limit) {
3818
+ this.config.limit = limit;
3819
+ return this;
3820
+ }
3821
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
3822
+ this.config.returning = orderSelectedFields(fields);
3823
+ return this;
3824
+ }
3825
+ /** @internal */
3826
+ getSQL() {
3827
+ return this.dialect.buildUpdateQuery(this.config);
3828
+ }
3829
+ toSQL() {
3830
+ const { typings: _typings,...rest } = this.dialect.sqlToQuery(this.getSQL());
3831
+ return rest;
3832
+ }
3833
+ /** @internal */
3834
+ _prepare(isOneTimeQuery = true) {
3835
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, void 0, {
3836
+ type: "insert",
3837
+ tables: extractUsedTable(this.config.table)
3838
+ });
3839
+ }
3840
+ prepare() {
3841
+ return this._prepare(false);
3842
+ }
3843
+ run = (placeholderValues) => {
3844
+ return this._prepare().run(placeholderValues);
3845
+ };
3846
+ all = (placeholderValues) => {
3847
+ return this._prepare().all(placeholderValues);
3848
+ };
3849
+ get = (placeholderValues) => {
3850
+ return this._prepare().get(placeholderValues);
3851
+ };
3852
+ values = (placeholderValues) => {
3853
+ return this._prepare().values(placeholderValues);
3854
+ };
3855
+ async execute() {
3856
+ return this.config.returning ? this.all() : this.run();
3857
+ }
3858
+ $dynamic() {
3859
+ return this;
3860
+ }
3861
+ };
3862
+
3863
+ //#endregion
3864
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/query-builders/count.js
3865
+ var SQLiteCountBuilder = class SQLiteCountBuilder extends SQL {
3866
+ constructor(params) {
3867
+ super(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
3868
+ this.params = params;
3869
+ this.session = params.session;
3870
+ this.sql = SQLiteCountBuilder.buildCount(params.source, params.filters);
3871
+ }
3872
+ sql;
3873
+ static [entityKind] = "SQLiteCountBuilderAsync";
3874
+ [Symbol.toStringTag] = "SQLiteCountBuilderAsync";
3875
+ session;
3876
+ static buildEmbeddedCount(source, filters) {
3877
+ return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
3878
+ }
3879
+ static buildCount(source, filters) {
3880
+ return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`;
3881
+ }
3882
+ then(onfulfilled, onrejected) {
3883
+ return Promise.resolve(this.session.count(this.sql)).then(onfulfilled, onrejected);
3884
+ }
3885
+ catch(onRejected) {
3886
+ return this.then(void 0, onRejected);
3887
+ }
3888
+ finally(onFinally) {
3889
+ return this.then((value) => {
3890
+ onFinally?.();
3891
+ return value;
3892
+ }, (reason) => {
3893
+ onFinally?.();
3894
+ throw reason;
3895
+ });
3896
+ }
3897
+ };
3898
+
3899
+ //#endregion
3900
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/query-builders/query.js
3901
+ var RelationalQueryBuilder = class {
3902
+ constructor(mode, fullSchema, schema, tableNamesMap, table, tableConfig, dialect$1, session) {
3903
+ this.mode = mode;
3904
+ this.fullSchema = fullSchema;
3905
+ this.schema = schema;
3906
+ this.tableNamesMap = tableNamesMap;
3907
+ this.table = table;
3908
+ this.tableConfig = tableConfig;
3909
+ this.dialect = dialect$1;
3910
+ this.session = session;
3911
+ }
3912
+ static [entityKind] = "SQLiteAsyncRelationalQueryBuilder";
3913
+ findMany(config) {
3914
+ return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many");
3915
+ }
3916
+ findFirst(config) {
3917
+ return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? {
3918
+ ...config,
3919
+ limit: 1
3920
+ } : { limit: 1 }, "first") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? {
3921
+ ...config,
3922
+ limit: 1
3923
+ } : { limit: 1 }, "first");
3924
+ }
3925
+ };
3926
+ var SQLiteRelationalQuery = class extends QueryPromise {
3927
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect$1, session, config, mode) {
3928
+ super();
3929
+ this.fullSchema = fullSchema;
3930
+ this.schema = schema;
3931
+ this.tableNamesMap = tableNamesMap;
3932
+ this.table = table;
3933
+ this.tableConfig = tableConfig;
3934
+ this.dialect = dialect$1;
3935
+ this.session = session;
3936
+ this.config = config;
3937
+ this.mode = mode;
3938
+ }
3939
+ static [entityKind] = "SQLiteAsyncRelationalQuery";
3940
+ /** @internal */
3941
+ mode;
3942
+ /** @internal */
3943
+ getSQL() {
3944
+ return this.dialect.buildRelationalQuery({
3945
+ fullSchema: this.fullSchema,
3946
+ schema: this.schema,
3947
+ tableNamesMap: this.tableNamesMap,
3948
+ table: this.table,
3949
+ tableConfig: this.tableConfig,
3950
+ queryConfig: this.config,
3951
+ tableAlias: this.tableConfig.tsName
3952
+ }).sql;
3953
+ }
3954
+ /** @internal */
3955
+ _prepare(isOneTimeQuery = false) {
3956
+ const { query, builtQuery } = this._toSQL();
3957
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](builtQuery, void 0, this.mode === "first" ? "get" : "all", true, (rawRows, mapColumnValue) => {
3958
+ const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue));
3959
+ if (this.mode === "first") return rows[0];
3960
+ return rows;
3961
+ });
3962
+ }
3963
+ prepare() {
3964
+ return this._prepare(false);
3965
+ }
3966
+ _toSQL() {
3967
+ const query = this.dialect.buildRelationalQuery({
3968
+ fullSchema: this.fullSchema,
3969
+ schema: this.schema,
3970
+ tableNamesMap: this.tableNamesMap,
3971
+ table: this.table,
3972
+ tableConfig: this.tableConfig,
3973
+ queryConfig: this.config,
3974
+ tableAlias: this.tableConfig.tsName
3975
+ });
3976
+ return {
3977
+ query,
3978
+ builtQuery: this.dialect.sqlToQuery(query.sql)
3979
+ };
3980
+ }
3981
+ toSQL() {
3982
+ return this._toSQL().builtQuery;
3983
+ }
3984
+ /** @internal */
3985
+ executeRaw() {
3986
+ if (this.mode === "first") return this._prepare(false).get();
3987
+ return this._prepare(false).all();
3988
+ }
3989
+ async execute() {
3990
+ return this.executeRaw();
3991
+ }
3992
+ };
3993
+ var SQLiteSyncRelationalQuery = class extends SQLiteRelationalQuery {
3994
+ static [entityKind] = "SQLiteSyncRelationalQuery";
3995
+ sync() {
3996
+ return this.executeRaw();
3997
+ }
3998
+ };
3999
+
4000
+ //#endregion
4001
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/query-builders/raw.js
4002
+ var SQLiteRaw = class extends QueryPromise {
4003
+ constructor(execute, getSQL, action, dialect$1, mapBatchResult) {
4004
+ super();
4005
+ this.execute = execute;
4006
+ this.getSQL = getSQL;
4007
+ this.dialect = dialect$1;
4008
+ this.mapBatchResult = mapBatchResult;
4009
+ this.config = { action };
4010
+ }
4011
+ static [entityKind] = "SQLiteRaw";
4012
+ /** @internal */
4013
+ config;
4014
+ getQuery() {
4015
+ return {
4016
+ ...this.dialect.sqlToQuery(this.getSQL()),
4017
+ method: this.config.action
4018
+ };
4019
+ }
4020
+ mapResult(result, isFromBatch) {
4021
+ return isFromBatch ? this.mapBatchResult(result) : result;
4022
+ }
4023
+ _prepare() {
4024
+ return this;
4025
+ }
4026
+ /** @internal */
4027
+ isResponseInArrayMode() {
4028
+ return false;
4029
+ }
4030
+ };
4031
+
4032
+ //#endregion
4033
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/db.js
4034
+ var BaseSQLiteDatabase = class {
4035
+ constructor(resultKind, dialect$1, session, schema) {
4036
+ this.resultKind = resultKind;
4037
+ this.dialect = dialect$1;
4038
+ this.session = session;
4039
+ this._ = schema ? {
4040
+ schema: schema.schema,
4041
+ fullSchema: schema.fullSchema,
4042
+ tableNamesMap: schema.tableNamesMap
4043
+ } : {
4044
+ schema: void 0,
4045
+ fullSchema: {},
4046
+ tableNamesMap: {}
4047
+ };
4048
+ this.query = {};
4049
+ const query = this.query;
4050
+ if (this._.schema) for (const [tableName, columns$1] of Object.entries(this._.schema)) query[tableName] = new RelationalQueryBuilder(resultKind, schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns$1, dialect$1, session);
4051
+ this.$cache = { invalidate: async (_params) => {} };
4052
+ }
4053
+ static [entityKind] = "BaseSQLiteDatabase";
4054
+ query;
4055
+ /**
4056
+ * Creates a subquery that defines a temporary named result set as a CTE.
4057
+ *
4058
+ * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
4059
+ *
4060
+ * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
4061
+ *
4062
+ * @param alias The alias for the subquery.
4063
+ *
4064
+ * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
4065
+ *
4066
+ * @example
4067
+ *
4068
+ * ```ts
4069
+ * // Create a subquery with alias 'sq' and use it in the select query
4070
+ * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
4071
+ *
4072
+ * const result = await db.with(sq).select().from(sq);
4073
+ * ```
4074
+ *
4075
+ * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
4076
+ *
4077
+ * ```ts
4078
+ * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
4079
+ * const sq = db.$with('sq').as(db.select({
4080
+ * name: sql<string>`upper(${users.name})`.as('name'),
4081
+ * })
4082
+ * .from(users));
4083
+ *
4084
+ * const result = await db.with(sq).select({ name: sq.name }).from(sq);
4085
+ * ```
4086
+ */
4087
+ $with = (alias, selection) => {
4088
+ const self = this;
4089
+ const as = (qb) => {
4090
+ if (typeof qb === "function") qb = qb(new QueryBuilder(self.dialect));
4091
+ return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({
4092
+ alias,
4093
+ sqlAliasedBehavior: "alias",
4094
+ sqlBehavior: "error"
4095
+ }));
4096
+ };
4097
+ return { as };
4098
+ };
4099
+ $count(source, filters) {
4100
+ return new SQLiteCountBuilder({
4101
+ source,
4102
+ filters,
4103
+ session: this.session
4104
+ });
4105
+ }
4106
+ /**
4107
+ * Incorporates a previously defined CTE (using `$with`) into the main query.
4108
+ *
4109
+ * This method allows the main query to reference a temporary named result set.
4110
+ *
4111
+ * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
4112
+ *
4113
+ * @param queries The CTEs to incorporate into the main query.
4114
+ *
4115
+ * @example
4116
+ *
4117
+ * ```ts
4118
+ * // Define a subquery 'sq' as a CTE using $with
4119
+ * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
4120
+ *
4121
+ * // Incorporate the CTE 'sq' into the main query and select from it
4122
+ * const result = await db.with(sq).select().from(sq);
4123
+ * ```
4124
+ */
4125
+ with(...queries) {
4126
+ const self = this;
4127
+ function select(fields) {
4128
+ return new SQLiteSelectBuilder({
4129
+ fields: fields ?? void 0,
4130
+ session: self.session,
4131
+ dialect: self.dialect,
4132
+ withList: queries
4133
+ });
4134
+ }
4135
+ function selectDistinct(fields) {
4136
+ return new SQLiteSelectBuilder({
4137
+ fields: fields ?? void 0,
4138
+ session: self.session,
4139
+ dialect: self.dialect,
4140
+ withList: queries,
4141
+ distinct: true
4142
+ });
4143
+ }
4144
+ function update(table) {
4145
+ return new SQLiteUpdateBuilder(table, self.session, self.dialect, queries);
4146
+ }
4147
+ function insert(into) {
4148
+ return new SQLiteInsertBuilder(into, self.session, self.dialect, queries);
4149
+ }
4150
+ function delete_(from) {
4151
+ return new SQLiteDeleteBase(from, self.session, self.dialect, queries);
4152
+ }
4153
+ return {
4154
+ select,
4155
+ selectDistinct,
4156
+ update,
4157
+ insert,
4158
+ delete: delete_
4159
+ };
4160
+ }
4161
+ select(fields) {
4162
+ return new SQLiteSelectBuilder({
4163
+ fields: fields ?? void 0,
4164
+ session: this.session,
4165
+ dialect: this.dialect
4166
+ });
4167
+ }
4168
+ selectDistinct(fields) {
4169
+ return new SQLiteSelectBuilder({
4170
+ fields: fields ?? void 0,
4171
+ session: this.session,
4172
+ dialect: this.dialect,
4173
+ distinct: true
4174
+ });
4175
+ }
4176
+ /**
4177
+ * Creates an update query.
4178
+ *
4179
+ * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
4180
+ *
4181
+ * Use `.set()` method to specify which values to update.
4182
+ *
4183
+ * See docs: {@link https://orm.drizzle.team/docs/update}
4184
+ *
4185
+ * @param table The table to update.
4186
+ *
4187
+ * @example
4188
+ *
4189
+ * ```ts
4190
+ * // Update all rows in the 'cars' table
4191
+ * await db.update(cars).set({ color: 'red' });
4192
+ *
4193
+ * // Update rows with filters and conditions
4194
+ * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
4195
+ *
4196
+ * // Update with returning clause
4197
+ * const updatedCar: Car[] = await db.update(cars)
4198
+ * .set({ color: 'red' })
4199
+ * .where(eq(cars.id, 1))
4200
+ * .returning();
4201
+ * ```
4202
+ */
4203
+ update(table) {
4204
+ return new SQLiteUpdateBuilder(table, this.session, this.dialect);
4205
+ }
4206
+ $cache;
4207
+ /**
4208
+ * Creates an insert query.
4209
+ *
4210
+ * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
4211
+ *
4212
+ * See docs: {@link https://orm.drizzle.team/docs/insert}
4213
+ *
4214
+ * @param table The table to insert into.
4215
+ *
4216
+ * @example
4217
+ *
4218
+ * ```ts
4219
+ * // Insert one row
4220
+ * await db.insert(cars).values({ brand: 'BMW' });
4221
+ *
4222
+ * // Insert multiple rows
4223
+ * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
4224
+ *
4225
+ * // Insert with returning clause
4226
+ * const insertedCar: Car[] = await db.insert(cars)
4227
+ * .values({ brand: 'BMW' })
4228
+ * .returning();
4229
+ * ```
4230
+ */
4231
+ insert(into) {
4232
+ return new SQLiteInsertBuilder(into, this.session, this.dialect);
4233
+ }
4234
+ /**
4235
+ * Creates a delete query.
4236
+ *
4237
+ * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
4238
+ *
4239
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
4240
+ *
4241
+ * @param table The table to delete from.
4242
+ *
4243
+ * @example
4244
+ *
4245
+ * ```ts
4246
+ * // Delete all rows in the 'cars' table
4247
+ * await db.delete(cars);
4248
+ *
4249
+ * // Delete rows with filters and conditions
4250
+ * await db.delete(cars).where(eq(cars.color, 'green'));
4251
+ *
4252
+ * // Delete with returning clause
4253
+ * const deletedCar: Car[] = await db.delete(cars)
4254
+ * .where(eq(cars.id, 1))
4255
+ * .returning();
4256
+ * ```
4257
+ */
4258
+ delete(from) {
4259
+ return new SQLiteDeleteBase(from, this.session, this.dialect);
4260
+ }
4261
+ run(query) {
4262
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
4263
+ if (this.resultKind === "async") return new SQLiteRaw(async () => this.session.run(sequel), () => sequel, "run", this.dialect, this.session.extractRawRunValueFromBatchResult.bind(this.session));
4264
+ return this.session.run(sequel);
4265
+ }
4266
+ all(query) {
4267
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
4268
+ if (this.resultKind === "async") return new SQLiteRaw(async () => this.session.all(sequel), () => sequel, "all", this.dialect, this.session.extractRawAllValueFromBatchResult.bind(this.session));
4269
+ return this.session.all(sequel);
4270
+ }
4271
+ get(query) {
4272
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
4273
+ if (this.resultKind === "async") return new SQLiteRaw(async () => this.session.get(sequel), () => sequel, "get", this.dialect, this.session.extractRawGetValueFromBatchResult.bind(this.session));
4274
+ return this.session.get(sequel);
4275
+ }
4276
+ values(query) {
4277
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
4278
+ if (this.resultKind === "async") return new SQLiteRaw(async () => this.session.values(sequel), () => sequel, "values", this.dialect, this.session.extractRawValuesValueFromBatchResult.bind(this.session));
4279
+ return this.session.values(sequel);
4280
+ }
4281
+ transaction(transaction, config) {
4282
+ return this.session.transaction(transaction, config);
4283
+ }
4284
+ };
4285
+
4286
+ //#endregion
4287
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/cache/core/cache.js
4288
+ var Cache = class {
4289
+ static [entityKind] = "Cache";
4290
+ };
4291
+ var NoopCache = class extends Cache {
4292
+ strategy() {
4293
+ return "all";
4294
+ }
4295
+ static [entityKind] = "NoopCache";
4296
+ async get(_key) {}
4297
+ async put(_hashedQuery, _response, _tables, _config) {}
4298
+ async onMutate(_params) {}
4299
+ };
4300
+ async function hashQuery(sql$1, params) {
4301
+ const dataToHash = `${sql$1}-${JSON.stringify(params)}`;
4302
+ const data = new TextEncoder().encode(dataToHash);
4303
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
4304
+ return [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
4305
+ }
4306
+
4307
+ //#endregion
4308
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/sqlite-core/session.js
4309
+ var ExecuteResultSync = class extends QueryPromise {
4310
+ constructor(resultCb) {
4311
+ super();
4312
+ this.resultCb = resultCb;
4313
+ }
4314
+ static [entityKind] = "ExecuteResultSync";
4315
+ async execute() {
4316
+ return this.resultCb();
4317
+ }
4318
+ sync() {
4319
+ return this.resultCb();
4320
+ }
4321
+ };
4322
+ var SQLitePreparedQuery = class {
4323
+ constructor(mode, executeMethod, query, cache, queryMetadata, cacheConfig) {
4324
+ this.mode = mode;
4325
+ this.executeMethod = executeMethod;
4326
+ this.query = query;
4327
+ this.cache = cache;
4328
+ this.queryMetadata = queryMetadata;
4329
+ this.cacheConfig = cacheConfig;
4330
+ if (cache && cache.strategy() === "all" && cacheConfig === void 0) this.cacheConfig = {
4331
+ enable: true,
4332
+ autoInvalidate: true
4333
+ };
4334
+ if (!this.cacheConfig?.enable) this.cacheConfig = void 0;
4335
+ }
4336
+ static [entityKind] = "PreparedQuery";
4337
+ /** @internal */
4338
+ joinsNotNullableMap;
4339
+ /** @internal */
4340
+ async queryWithCache(queryString, params, query) {
4341
+ if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) try {
4342
+ return await query();
4343
+ } catch (e) {
4344
+ throw new DrizzleQueryError(queryString, params, e);
4345
+ }
4346
+ if (this.cacheConfig && !this.cacheConfig.enable) try {
4347
+ return await query();
4348
+ } catch (e) {
4349
+ throw new DrizzleQueryError(queryString, params, e);
4350
+ }
4351
+ if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) try {
4352
+ const [res] = await Promise.all([query(), this.cache.onMutate({ tables: this.queryMetadata.tables })]);
4353
+ return res;
4354
+ } catch (e) {
4355
+ throw new DrizzleQueryError(queryString, params, e);
4356
+ }
4357
+ if (!this.cacheConfig) try {
4358
+ return await query();
4359
+ } catch (e) {
4360
+ throw new DrizzleQueryError(queryString, params, e);
4361
+ }
4362
+ if (this.queryMetadata.type === "select") {
4363
+ const fromCache = await this.cache.get(this.cacheConfig.tag ?? await hashQuery(queryString, params), this.queryMetadata.tables, this.cacheConfig.tag !== void 0, this.cacheConfig.autoInvalidate);
4364
+ if (fromCache === void 0) {
4365
+ let result;
4366
+ try {
4367
+ result = await query();
4368
+ } catch (e) {
4369
+ throw new DrizzleQueryError(queryString, params, e);
4370
+ }
4371
+ await this.cache.put(this.cacheConfig.tag ?? await hashQuery(queryString, params), result, this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], this.cacheConfig.tag !== void 0, this.cacheConfig.config);
4372
+ return result;
4373
+ }
4374
+ return fromCache;
4375
+ }
4376
+ try {
4377
+ return await query();
4378
+ } catch (e) {
4379
+ throw new DrizzleQueryError(queryString, params, e);
4380
+ }
4381
+ }
4382
+ getQuery() {
4383
+ return this.query;
4384
+ }
4385
+ mapRunResult(result, _isFromBatch) {
4386
+ return result;
4387
+ }
4388
+ mapAllResult(_result, _isFromBatch) {
4389
+ throw new Error("Not implemented");
4390
+ }
4391
+ mapGetResult(_result, _isFromBatch) {
4392
+ throw new Error("Not implemented");
4393
+ }
4394
+ execute(placeholderValues) {
4395
+ if (this.mode === "async") return this[this.executeMethod](placeholderValues);
4396
+ return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));
4397
+ }
4398
+ mapResult(response, isFromBatch) {
4399
+ switch (this.executeMethod) {
4400
+ case "run": return this.mapRunResult(response, isFromBatch);
4401
+ case "all": return this.mapAllResult(response, isFromBatch);
4402
+ case "get": return this.mapGetResult(response, isFromBatch);
4403
+ }
4404
+ }
4405
+ };
4406
+ var SQLiteSession = class {
4407
+ constructor(dialect$1) {
4408
+ this.dialect = dialect$1;
4409
+ }
4410
+ static [entityKind] = "SQLiteSession";
4411
+ prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
4412
+ return this.prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig);
4413
+ }
4414
+ run(query) {
4415
+ const staticQuery = this.dialect.sqlToQuery(query);
4416
+ try {
4417
+ return this.prepareOneTimeQuery(staticQuery, void 0, "run", false).run();
4418
+ } catch (err) {
4419
+ throw new DrizzleError({
4420
+ cause: err,
4421
+ message: `Failed to run the query '${staticQuery.sql}'`
4422
+ });
4423
+ }
4424
+ }
4425
+ /** @internal */
4426
+ extractRawRunValueFromBatchResult(result) {
4427
+ return result;
4428
+ }
4429
+ all(query) {
4430
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).all();
4431
+ }
4432
+ /** @internal */
4433
+ extractRawAllValueFromBatchResult(_result) {
4434
+ throw new Error("Not implemented");
4435
+ }
4436
+ get(query) {
4437
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).get();
4438
+ }
4439
+ /** @internal */
4440
+ extractRawGetValueFromBatchResult(_result) {
4441
+ throw new Error("Not implemented");
4442
+ }
4443
+ values(query) {
4444
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).values();
4445
+ }
4446
+ async count(sql$1) {
4447
+ return (await this.values(sql$1))[0][0];
4448
+ }
4449
+ /** @internal */
4450
+ extractRawValuesValueFromBatchResult(_result) {
4451
+ throw new Error("Not implemented");
4452
+ }
4453
+ };
4454
+ var SQLiteTransaction = class extends BaseSQLiteDatabase {
4455
+ constructor(resultType, dialect$1, session, schema, nestedIndex = 0) {
4456
+ super(resultType, dialect$1, session, schema);
4457
+ this.schema = schema;
4458
+ this.nestedIndex = nestedIndex;
4459
+ }
4460
+ static [entityKind] = "SQLiteTransaction";
4461
+ rollback() {
4462
+ throw new TransactionRollbackError();
4463
+ }
4464
+ };
4465
+
4466
+ //#endregion
4467
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/durable-sqlite/session.js
4468
+ var SQLiteDOSession = class extends SQLiteSession {
4469
+ constructor(client, dialect$1, schema, options = {}) {
4470
+ super(dialect$1);
4471
+ this.client = client;
4472
+ this.schema = schema;
4473
+ this.logger = options.logger ?? new NoopLogger();
4474
+ }
4475
+ static [entityKind] = "SQLiteDOSession";
4476
+ logger;
4477
+ prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper) {
4478
+ return new SQLiteDOPreparedQuery(this.client, query, this.logger, fields, executeMethod, isResponseInArrayMode, customResultMapper);
4479
+ }
4480
+ transaction(transaction, _config) {
4481
+ const tx = new SQLiteDOTransaction("sync", this.dialect, this, this.schema);
4482
+ this.client.transactionSync(() => {
4483
+ transaction(tx);
4484
+ });
4485
+ return {};
4486
+ }
4487
+ };
4488
+ var SQLiteDOTransaction = class SQLiteDOTransaction extends SQLiteTransaction {
4489
+ static [entityKind] = "SQLiteDOTransaction";
4490
+ transaction(transaction) {
4491
+ const tx = new SQLiteDOTransaction("sync", this.dialect, this.session, this.schema, this.nestedIndex + 1);
4492
+ this.session.transaction(() => transaction(tx));
4493
+ return {};
4494
+ }
4495
+ };
4496
+ var SQLiteDOPreparedQuery = class extends SQLitePreparedQuery {
4497
+ constructor(client, query, logger, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {
4498
+ super("sync", executeMethod, query, void 0, void 0, void 0);
4499
+ this.client = client;
4500
+ this.logger = logger;
4501
+ this.fields = fields;
4502
+ this._isResponseInArrayMode = _isResponseInArrayMode;
4503
+ this.customResultMapper = customResultMapper;
4504
+ }
4505
+ static [entityKind] = "SQLiteDOPreparedQuery";
4506
+ run(placeholderValues) {
4507
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
4508
+ this.logger.logQuery(this.query.sql, params);
4509
+ params.length > 0 ? this.client.sql.exec(this.query.sql, ...params) : this.client.sql.exec(this.query.sql);
4510
+ }
4511
+ all(placeholderValues) {
4512
+ const { fields, joinsNotNullableMap, query, logger, client, customResultMapper } = this;
4513
+ if (!fields && !customResultMapper) {
4514
+ const params = fillPlaceholders(query.params, placeholderValues ?? {});
4515
+ logger.logQuery(query.sql, params);
4516
+ return params.length > 0 ? client.sql.exec(query.sql, ...params).toArray() : client.sql.exec(query.sql).toArray();
4517
+ }
4518
+ const rows = this.values(placeholderValues);
4519
+ if (customResultMapper) return customResultMapper(rows);
4520
+ return rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
4521
+ }
4522
+ get(placeholderValues) {
4523
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
4524
+ this.logger.logQuery(this.query.sql, params);
4525
+ const { fields, client, joinsNotNullableMap, customResultMapper, query } = this;
4526
+ if (!fields && !customResultMapper) return (params.length > 0 ? client.sql.exec(query.sql, ...params) : client.sql.exec(query.sql)).next().value;
4527
+ const rows = this.values(placeholderValues);
4528
+ const row = rows[0];
4529
+ if (!row) return;
4530
+ if (customResultMapper) return customResultMapper(rows);
4531
+ return mapResultRow(fields, row, joinsNotNullableMap);
4532
+ }
4533
+ values(placeholderValues) {
4534
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
4535
+ this.logger.logQuery(this.query.sql, params);
4536
+ return (params.length > 0 ? this.client.sql.exec(this.query.sql, ...params) : this.client.sql.exec(this.query.sql)).raw().toArray();
4537
+ }
4538
+ /** @internal */
4539
+ isResponseInArrayMode() {
4540
+ return this._isResponseInArrayMode;
4541
+ }
4542
+ };
4543
+
4544
+ //#endregion
4545
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/durable-sqlite/driver.js
4546
+ var DrizzleSqliteDODatabase = class extends BaseSQLiteDatabase {
4547
+ static [entityKind] = "DrizzleSqliteDODatabase";
4548
+ };
4549
+ function drizzle(client, config = {}) {
4550
+ const dialect$1 = new SQLiteSyncDialect({ casing: config.casing });
4551
+ let logger;
4552
+ if (config.logger === true) logger = new DefaultLogger();
4553
+ else if (config.logger !== false) logger = config.logger;
4554
+ let schema;
4555
+ if (config.schema) {
4556
+ const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);
4557
+ schema = {
4558
+ fullSchema: config.schema,
4559
+ schema: tablesConfig.tables,
4560
+ tableNamesMap: tablesConfig.tableNamesMap
4561
+ };
4562
+ }
4563
+ const db = new DrizzleSqliteDODatabase("sync", dialect$1, new SQLiteDOSession(client, dialect$1, schema, { logger }), schema);
4564
+ db.$client = client;
4565
+ return db;
4566
+ }
4567
+
4568
+ //#endregion
4569
+ //#region ../node_modules/.bun/drizzle-orm@0.44.6+18fa98f9a11657f9/node_modules/drizzle-orm/durable-sqlite/migrator.js
4570
+ function readMigrationFiles({ journal, migrations }) {
4571
+ const migrationQueries = [];
4572
+ for (const journalEntry of journal.entries) {
4573
+ const query = migrations[`m${journalEntry.idx.toString().padStart(4, "0")}`];
4574
+ if (!query) throw new Error(`Missing migration: ${journalEntry.tag}`);
4575
+ try {
4576
+ const result = query.split("--> statement-breakpoint").map((it) => {
4577
+ return it;
4578
+ });
4579
+ migrationQueries.push({
4580
+ sql: result,
4581
+ bps: journalEntry.breakpoints,
4582
+ folderMillis: journalEntry.when,
4583
+ hash: ""
4584
+ });
4585
+ } catch {
4586
+ throw new Error(`Failed to parse migration: ${journalEntry.tag}`);
4587
+ }
4588
+ }
4589
+ return migrationQueries;
4590
+ }
4591
+ async function migrate(db, config) {
4592
+ const migrations = readMigrationFiles(config);
4593
+ db.transaction((tx) => {
4594
+ try {
4595
+ const migrationsTable = "__drizzle_migrations";
4596
+ const migrationTableCreate = sql`
4597
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
16
4598
  id SERIAL PRIMARY KEY,
17
4599
  hash text NOT NULL,
18
4600
  created_at numeric
19
4601
  )
20
- `;r.run(n);let u=r.values(o`SELECT id, hash, created_at FROM ${o.identifier(i)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;for(let f of t)if(!u||Number(u[2])<f.folderMillis){for(let d of f.sql)r.run(o.raw(d));r.run(o`INSERT INTO ${o.identifier(i)} ("hash", "created_at") VALUES(${f.hash}, ${f.folderMillis})`)}}catch(i){throw s.rollback(),i}})}var qs={version:"7",dialect:"sqlite",entries:[{idx:0,version:"6",when:1752097986271,tag:"0000_far_moon_knight",breakpoints:!0}]};var vs="CREATE TABLE `resources` (\n `id` text NOT NULL,\n `scope` text NOT NULL,\n `status` text NOT NULL,\n `kind` text NOT NULL,\n `fqn` text NOT NULL,\n `seq` integer NOT NULL,\n `data` text NOT NULL,\n `props` text,\n `oldProps` text,\n `output` text NOT NULL,\n PRIMARY KEY(`scope`, `id`)\n);\n";var Qs={journal:qs,migrations:{m0000:vs}};function Ls(r,e){throw new Error(e??`Unexpected value: ${JSON.stringify(r)}`)}var ft={};js(ft,{resources:()=>q});var q=xs("resources",{id:U("id").notNull(),scope:U("scope",{mode:"json"}).$type().notNull(),status:U("status",{enum:["creating","created","updating","updated","deleting","deleted"]}).notNull(),kind:U("kind").notNull(),fqn:U("fqn").notNull(),seq:Ye("seq").notNull(),data:U("data",{mode:"json"}).notNull().$type(),props:U("props",{mode:"json"}).$type(),oldProps:U("oldProps",{mode:"json"}).$type(),output:U("output",{mode:"json"}).notNull().$type()},r=>[Cs({columns:[r.scope,r.id]})]);var{scope:iu,...Cr}=ze(q),ht=class{constructor(e,t){this.db=e;this.context=t}async dispatch(e,t){switch(e){case"init":return;case"deinit":return;case"list":return this.list();case"count":return this.count();case"get":{let[s]=t;return this.get(s)}case"getBatch":{let[s]=t;return this.getBatch(s)}case"all":return this.all();case"set":{let[s,i]=t;return this.set(s,i)}case"delete":{let[s]=t;return this.delete(s)}default:Ls(e)}}async list(){return(await this.db.select({id:q.id}).from(q).where(M(q.scope,this.context.chain))).map(t=>t.id)}async count(){return await this.db.$count(this.db.select().from(q).where(M(q.scope,this.context.chain)))}async get(e){let[t]=await this.db.select(Cr).from(q).where(te(M(q.scope,this.context.chain),M(q.id,e)));if(t)return{...t,props:t.props??void 0,oldProps:t.oldProps??void 0}}async all(){let e=await this.db.select(Cr).from(q).where(M(q.scope,this.context.chain)),t={};for(let s of e)t[s.id]={...s,props:s.props??void 0,oldProps:s.oldProps??void 0};return t}async set(e,t){await this.db.insert(q).values({...t,scope:this.context.chain}).onConflictDoUpdate({target:[q.id,q.scope],set:{...t}})}async delete(e){await this.db.delete(q).where(te(M(q.scope,this.context.chain),M(q.id,e)))}async getBatch(e){let t=await this.db.select(Cr).from(q).where(te(M(q.scope,this.context.chain),Je(q.id,e))),s={};for(let i of t)s[i.id]={...i,props:i.props??void 0,oldProps:i.oldProps??void 0};return s}};var ei=async(r,e)=>{let t=new TextEncoder,s=r.headers.get("Authorization")?.split(" ")[1];if(!s)return!1;let i=await crypto.subtle.digest("SHA-256",t.encode(e.STATE_TOKEN)),n=await crypto.subtle.digest("SHA-256",t.encode(s));return await crypto.subtle.timingSafeEqual(i,n)},mu={fetch:async(r,e)=>{if(!await ei(r,e))return Response.json({success:!1,status:401,error:"Unauthorized"},{status:401});if(r.method==="HEAD")return new Response(null,{status:200});if(r.method!=="POST")return Response.json({success:!1,status:405,error:"Method not allowed"},{status:405});try{let t=e.STORE.get(e.STORE.idFromName("default")),s=await r.json(),i=await t.rpc(s);return Response.json({success:!0,status:200,result:i},{status:200})}catch(t){return console.error(t),Response.json({success:!1,status:500,error:String(t)},{status:500})}}},Os=class extends Xs{db=Ts(this.ctx.storage,{schema:ft});constructor(e,t){super(e,t),e.blockConcurrencyWhile(async()=>{await $s(this.db,Qs)})}async rpc(e){return new ht(this.db,{chain:e.context.chain}).dispatch(e.method,e.params)}};export{Os as Store,mu as default};
4602
+ `;
4603
+ db.run(migrationTableCreate);
4604
+ const lastDbMigration = db.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`)[0] ?? void 0;
4605
+ for (const migration of migrations) if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
4606
+ for (const stmt of migration.sql) db.run(sql.raw(stmt));
4607
+ db.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
4608
+ }
4609
+ } catch (error) {
4610
+ tx.rollback();
4611
+ throw error;
4612
+ }
4613
+ });
4614
+ }
4615
+
4616
+ //#endregion
4617
+ //#region drizzle/durable-object/meta/_journal.json
4618
+ var version = "7";
4619
+ var dialect = "sqlite";
4620
+ var entries = [{
4621
+ "idx": 0,
4622
+ "version": "6",
4623
+ "when": 1752097986271,
4624
+ "tag": "0000_far_moon_knight",
4625
+ "breakpoints": true
4626
+ }];
4627
+ var _journal_default = {
4628
+ version,
4629
+ dialect,
4630
+ entries
4631
+ };
4632
+
4633
+ //#endregion
4634
+ //#region drizzle/durable-object/0000_far_moon_knight.sql
4635
+ var _0000_far_moon_knight_default = "CREATE TABLE `resources` (\n `id` text NOT NULL,\n `scope` text NOT NULL,\n `status` text NOT NULL,\n `kind` text NOT NULL,\n `fqn` text NOT NULL,\n `seq` integer NOT NULL,\n `data` text NOT NULL,\n `props` text,\n `oldProps` text,\n `output` text NOT NULL,\n PRIMARY KEY(`scope`, `id`)\n);\n";
4636
+
4637
+ //#endregion
4638
+ //#region drizzle/durable-object/migrations.js
4639
+ var migrations_default = {
4640
+ journal: _journal_default,
4641
+ migrations: { m0000: _0000_far_moon_knight_default }
4642
+ };
4643
+
4644
+ //#endregion
4645
+ //#region src/util/assert-never.ts
4646
+ function assertNever(value, message) {
4647
+ throw new Error(message ?? `Unexpected value: ${JSON.stringify(value)}`);
4648
+ }
4649
+
4650
+ //#endregion
4651
+ //#region src/state/schema.ts
4652
+ var schema_exports = /* @__PURE__ */ __export({ resources: () => resources });
4653
+ const resources = sqliteTable("resources", {
4654
+ id: text("id").notNull(),
4655
+ scope: text("scope", { mode: "json" }).$type().notNull(),
4656
+ status: text("status", { enum: [
4657
+ "creating",
4658
+ "created",
4659
+ "updating",
4660
+ "updated",
4661
+ "deleting",
4662
+ "deleted"
4663
+ ] }).notNull(),
4664
+ kind: text("kind").notNull(),
4665
+ fqn: text("fqn").notNull(),
4666
+ seq: integer("seq").notNull(),
4667
+ data: text("data", { mode: "json" }).notNull().$type(),
4668
+ props: text("props", { mode: "json" }).$type(),
4669
+ oldProps: text("oldProps", { mode: "json" }).$type(),
4670
+ output: text("output", { mode: "json" }).notNull().$type()
4671
+ }, (t) => [primaryKey({ columns: [t.scope, t.id] })]);
4672
+
4673
+ //#endregion
4674
+ //#region src/state/operations.ts
4675
+ const { scope: _,...columns } = getTableColumns(resources);
4676
+ /**
4677
+ * Represents the SQL operations for a SQLite-backed state store.
4678
+ * DOES NOT include serialization/deserialization — that is handled by the `StateStoreProxy` class.
4679
+ */
4680
+ var SQLiteStateStoreOperations = class {
4681
+ constructor(db, context) {
4682
+ this.db = db;
4683
+ this.context = context;
4684
+ }
4685
+ async dispatch(method, params) {
4686
+ switch (method) {
4687
+ case "init": return;
4688
+ case "deinit": return;
4689
+ case "list": return this.list();
4690
+ case "count": return this.count();
4691
+ case "get": {
4692
+ const [key] = params;
4693
+ return this.get(key);
4694
+ }
4695
+ case "getBatch": {
4696
+ const [keys] = params;
4697
+ return this.getBatch(keys);
4698
+ }
4699
+ case "all": return this.all();
4700
+ case "set": {
4701
+ const [key, state] = params;
4702
+ return this.set(key, state);
4703
+ }
4704
+ case "delete": {
4705
+ const [key] = params;
4706
+ return this.delete(key);
4707
+ }
4708
+ default: assertNever(method);
4709
+ }
4710
+ }
4711
+ async list() {
4712
+ return (await this.db.select({ id: resources.id }).from(resources).where(eq(resources.scope, this.context.chain))).map((r) => r.id);
4713
+ }
4714
+ async count() {
4715
+ return await this.db.$count(this.db.select().from(resources).where(eq(resources.scope, this.context.chain)));
4716
+ }
4717
+ async get(key) {
4718
+ const [result] = await this.db.select(columns).from(resources).where(and(eq(resources.scope, this.context.chain), eq(resources.id, key)));
4719
+ if (!result) return;
4720
+ return {
4721
+ ...result,
4722
+ props: result.props ?? void 0,
4723
+ oldProps: result.oldProps ?? void 0
4724
+ };
4725
+ }
4726
+ async all() {
4727
+ const result = await this.db.select(columns).from(resources).where(eq(resources.scope, this.context.chain));
4728
+ const record = {};
4729
+ for (const r of result) record[r.id] = {
4730
+ ...r,
4731
+ props: r.props ?? void 0,
4732
+ oldProps: r.oldProps ?? void 0
4733
+ };
4734
+ return record;
4735
+ }
4736
+ async set(_key, state) {
4737
+ await this.db.insert(resources).values({
4738
+ ...state,
4739
+ scope: this.context.chain
4740
+ }).onConflictDoUpdate({
4741
+ target: [resources.id, resources.scope],
4742
+ set: { ...state }
4743
+ });
4744
+ }
4745
+ async delete(key) {
4746
+ await this.db.delete(resources).where(and(eq(resources.scope, this.context.chain), eq(resources.id, key)));
4747
+ }
4748
+ async getBatch(keys) {
4749
+ const result = await this.db.select(columns).from(resources).where(and(eq(resources.scope, this.context.chain), inArray(resources.id, keys)));
4750
+ const record = {};
4751
+ for (const r of result) record[r.id] = {
4752
+ ...r,
4753
+ props: r.props ?? void 0,
4754
+ oldProps: r.oldProps ?? void 0
4755
+ };
4756
+ return record;
4757
+ }
4758
+ };
4759
+
4760
+ //#endregion
4761
+ //#region workers/cloudflare-state-store.ts
4762
+ const validateRequest = async (request, env) => {
4763
+ const encoder = new TextEncoder();
4764
+ const token = request.headers.get("Authorization")?.split(" ")[1];
4765
+ if (!token) return false;
4766
+ const expected = await crypto.subtle.digest("SHA-256", encoder.encode(env.STATE_TOKEN));
4767
+ const actual = await crypto.subtle.digest("SHA-256", encoder.encode(token));
4768
+ return await crypto.subtle.timingSafeEqual(expected, actual);
4769
+ };
4770
+ var cloudflare_state_store_default = { fetch: async (request, env) => {
4771
+ if (!await validateRequest(request, env)) return Response.json({
4772
+ success: false,
4773
+ status: 401,
4774
+ error: "Unauthorized"
4775
+ }, { status: 401 });
4776
+ if (request.method === "HEAD") return new Response(null, { status: 200 });
4777
+ if (request.method !== "POST") return Response.json({
4778
+ success: false,
4779
+ status: 405,
4780
+ error: "Method not allowed"
4781
+ }, { status: 405 });
4782
+ try {
4783
+ const store = env.STORE.get(env.STORE.idFromName("default"));
4784
+ const body = await request.json();
4785
+ const result = await store.rpc(body);
4786
+ return Response.json({
4787
+ success: true,
4788
+ status: 200,
4789
+ result
4790
+ }, { status: 200 });
4791
+ } catch (e) {
4792
+ console.error(e);
4793
+ return Response.json({
4794
+ success: false,
4795
+ status: 500,
4796
+ error: String(e)
4797
+ }, { status: 500 });
4798
+ }
4799
+ } };
4800
+ var Store = class extends DurableObject {
4801
+ db = drizzle(this.ctx.storage, { schema: schema_exports });
4802
+ constructor(ctx, env) {
4803
+ super(ctx, env);
4804
+ ctx.blockConcurrencyWhile(async () => {
4805
+ await migrate(this.db, migrations_default);
4806
+ });
4807
+ }
4808
+ async rpc(request) {
4809
+ return new SQLiteStateStoreOperations(this.db, { chain: request.context.chain }).dispatch(request.method, request.params);
4810
+ }
4811
+ };
4812
+
4813
+ //#endregion
4814
+ export { Store, cloudflare_state_store_default as default };