@lunora/hyperdrive 1.0.0-alpha.107 → 1.0.0-alpha.108

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/global.mjs CHANGED
@@ -1 +1 @@
1
- import{createSqlCtxDb as c}from"@lunora/sql-store";import{postgresDialect as l,mysqlDialect as s}from"./packem_shared/mysqlDialect-CQoNqaB-.mjs";import{buildMysqlExec as a,buildPgExec as i}from"./packem_shared/buildMysqlExec-CPwtojyL.mjs";import{createPgVectorIndex as d}from"./packem_shared/createPgVectorIndex-DcpguGpe.mjs";const r=({engine:e,exec:t,...o})=>c({...o,dialect:e==="postgres"?l:s,exec:t}),p=(e,t)=>r({...t,engine:"postgres",exec:i(e)}),g=(e,t)=>r({...t,engine:"mysql",exec:a(e)});export{a as buildMysqlExec,i as buildPgExec,r as createHyperdriveGlobalCtxDb,g as createMysqlGlobalCtxDb,d as createPgVectorIndex,p as createPostgresGlobalCtxDb,s as mysqlDialect,l as postgresDialect};
1
+ import{createSqlCtxDb as c}from"@lunora/sql-store";import{postgresDialect as l,mysqlDialect as s}from"./packem_shared/mysqlDialect-B0_iJVGV.mjs";import{buildMysqlExec as a,buildPgExec as i}from"./packem_shared/buildMysqlExec-BTmXrDGL.mjs";import{createPgVectorIndex as d}from"./packem_shared/createPgVectorIndex-DtazJ48m.mjs";const r=({engine:e,exec:t,...o})=>c({...o,dialect:e==="postgres"?l:s,exec:t}),p=(e,t)=>r({...t,engine:"postgres",exec:i(e)}),g=(e,t)=>r({...t,engine:"mysql",exec:a(e)});export{a as buildMysqlExec,i as buildPgExec,r as createHyperdriveGlobalCtxDb,g as createMysqlGlobalCtxDb,d as createPgVectorIndex,p as createPostgresGlobalCtxDb,s as mysqlDialect,l as postgresDialect};
@@ -1 +1 @@
1
- import{LunoraError as o}from"@lunora/errors";const n=2,s=new WeakSet,i=r=>{const e=r.config?.clientFlags;if(typeof e=="number")return e;const t=r.pool?.config?.connectionConfig?.clientFlags;return typeof t=="number"?t:void 0},c=r=>{const e=i(r);if(e===void 0){if(s.has(r))return;s.add(r),console.warn('@lunora/hyperdrive: could not determine whether this MySQL connection negotiated CLIENT_FOUND_ROWS (the driver exposes no flag introspection). If it was NOT created with the `CLIENT_FOUND_ROWS` flag (mysql2: `createPool({ flags: ["FOUND_ROWS"] })`), an idempotent patch/replace that rewrites identical values may report 0 affectedRows and raise a spurious OCC ConflictError.');return}if((e&n)===0)throw new o("INTERNAL",'@lunora/hyperdrive: this MySQL connection was not created with the `CLIENT_FOUND_ROWS` flag (mysql2: `createPool({ flags: ["FOUND_ROWS"] })`). Without it, `affectedRows` counts changed (not matched) rows, so an idempotent patch/replace that rewrites identical values reports 0 and the OCC guard raises a spurious conflict.')},u=r=>({all:(e,t)=>r.query(e,t),batch:async e=>{await Promise.all(e.map(t=>r.query(t.sql,t.params)))},run:async(e,t)=>(await r.query(e,t),{rowsAffected:0})}),d=r=>(c(r),{all:async(e,t)=>{const[a]=await r.execute(e,t);return a},batch:async e=>{await Promise.all(e.map(t=>r.execute(t.sql,t.params)))},run:async(e,t)=>{const[a]=await r.execute(e,t);return{rowsAffected:a.affectedRows??0}}});export{d as buildMysqlExec,u as buildPgExec};
1
+ import{LunoraError as o}from"@lunora/errors";const n=2,s=new WeakSet,i=t=>{const e=t.config?.clientFlags;if(typeof e=="number")return e;const r=t.pool?.config?.connectionConfig?.clientFlags;return typeof r=="number"?r:void 0},c=t=>{const e=i(t);if(e===void 0){if(s.has(t))return;s.add(t),console.warn('@lunora/hyperdrive: could not determine whether this MySQL connection negotiated CLIENT_FOUND_ROWS (the driver exposes no flag introspection). If it was NOT created with the `CLIENT_FOUND_ROWS` flag (mysql2: `createPool({ flags: ["FOUND_ROWS"] })`), an idempotent patch/replace that rewrites identical values may report 0 affectedRows and raise a spurious OCC ConflictError.');return}if((e&n)===0)throw new o("INTERNAL",'@lunora/hyperdrive: this MySQL connection was not created with the `CLIENT_FOUND_ROWS` flag (mysql2: `createPool({ flags: ["FOUND_ROWS"] })`). Without it, `affectedRows` counts changed (not matched) rows, so an idempotent patch/replace that rewrites identical values reports 0 and the OCC guard raises a spurious conflict.')},u=t=>({all:(e,r)=>t.query(e,r),batch:async e=>{await Promise.all(e.map(r=>t.query(r.sql,r.params)))},run:async(e,r)=>(await t.query(e,r),{rowsAffected:0})}),d=t=>(c(t),{all:async(e,r)=>{const[a]=await t.execute(e,r);return Array.isArray(a)?a:[]},batch:async e=>{await Promise.all(e.map(r=>t.execute(r.sql,r.params)))},run:async(e,r)=>{const[a]=await t.execute(e,r);return{rowsAffected:a.affectedRows??0}}});export{d as buildMysqlExec,u as buildPgExec};
@@ -0,0 +1 @@
1
+ const j=t=>/^[A-Z_]\w*$/i.test(t);const x=new Set(["42P06","42P07","23505","42710"]),F=t=>typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&x.has(t.code),X=5,D="__vec_",v="__ann_",b={cosine:{operator:"<=>",operatorClass:"vector_cosine_ops",score:t=>1-t},"dot-product":{operator:"<#>",operatorClass:"vector_ip_ops",score:t=>t},euclidean:{operator:"<->",operatorClass:"vector_l2_ops",score:t=>t}},P=63,_=P-D.length-v.length-Math.max(...Object.values(b).map(t=>t.operatorClass.length)),A=t=>`[${t.join(",")}]`,C=t=>{const c=Object.getPrototypeOf(t);return c===null||c===Object.prototype},R=t=>t.constructor?.name??"non-plain object",J=(t,c)=>{const o=(e,r)=>{throw new TypeError(`@lunora/hyperdrive: pgvector index "${c}" supports equality metadata filters only, but "${r}" ${e}. Pre-compute it into an equality-shaped metadata field, or keep this index on Vectorize.`)},E=(e,r)=>{(e===void 0||typeof e=="function"||typeof e=="symbol")&&o(`has a value at "${r}" that JSON cannot represent, which would widen the filter to match every row`,r),typeof e=="number"&&!Number.isFinite(e)&&o(`has a non-finite number at "${r}", which JSON turns into null`,r),typeof e=="bigint"&&o(`has a bigint at "${r}", which JSON cannot serialise`,r)},m=(e,r)=>{if(E(e,r),Array.isArray(e)){for(const[p,l]of e.entries())m(l,`${r}[${String(p)}]`);return}if(!(typeof e!="object"||e===null)){C(e)||o(`is a ${R(e)}, whose fields JSON does not preserve`,r);for(const[p,l]of Object.entries(e))p.startsWith("$")&&o("uses a comparison operator",r),m(l,`${r}.${p}`)}};C(t)||o(`is a ${R(t)}, whose fields JSON does not preserve`,"filter");for(const[e,r]of Object.entries(t))e.startsWith("$")&&o("uses a comparison operator",e),e.includes(".")&&o("uses Vectorize's dot-addressed nested syntax, which JSONB containment cannot express",e),m(r,e)},U=t=>{if(!j(t))throw new TypeError(`@lunora/hyperdrive: pgvector \`name\` must be a bare SQL identifier (letters, digits, underscore; not starting with a digit) — got "${t}"`);if(t.length>_)throw new TypeError(`@lunora/hyperdrive: pgvector \`name\` must be at most ${String(_)} characters — got "${t}" (${String(t.length)}). Postgres truncates identifiers at 63 bytes and this index derives longer names from it.`);return t},H=t=>{const{client:c,dimensions:o,metric:E="cosine",name:m}=t,e=`${D}${U(m)}`;if(!Object.hasOwn(b,E))throw new TypeError(`@lunora/hyperdrive: pgvector index "${m}" got an unknown metric "${E}" — expected cosine, euclidean, or dot-product`);const{operator:r,operatorClass:p,score:l}=b[E];if(!Number.isInteger(o)||o<=0)throw new TypeError(`@lunora/hyperdrive: pgvector index "${m}" needs a positive integer \`dimensions\` — got ${String(o)}`);if(o>2e3)throw new TypeError(`@lunora/hyperdrive: pgvector index "${m}" declares ${String(o)} dimensions, over the HNSW limit of ${String(2e3)}. Reduce the embedding width (Vectorize itself tops out at 1536), or keep this index on Vectorize.`);let y=0;const S=()=>(y+=1,`${e}:${String(y)}`);let I;const $=async()=>(I??=(async()=>{for(const n of["CREATE EXTENSION IF NOT EXISTS vector",`CREATE TABLE IF NOT EXISTS "${e}" (id text PRIMARY KEY, namespace text, embedding vector(${String(o)}) NOT NULL, metadata jsonb)`,`CREATE INDEX IF NOT EXISTS "${e}${v}${p}" ON "${e}" USING hnsw (embedding ${p})`,`CREATE INDEX IF NOT EXISTS "${e}__ns" ON "${e}" (namespace)`,`CREATE INDEX IF NOT EXISTS "${e}__meta" ON "${e}" USING gin (metadata)`])try{await c.query(n)}catch(a){if(!F(a))throw a}})().catch(n=>{throw I=void 0,n}),I),O=async(n,a)=>{if(n.length===0)return{mutationId:S()};await $();const s=[...new Map(n.map(i=>[i.id,i])).values()],g=[],u=i=>`$${String(g.push(i))}`,N=s.map(i=>`(${u(i.id)}, ${u(i.namespace??null)}, ${u(A(i.values))}::vector, ${u(i.metadata===void 0?null:JSON.stringify(i.metadata))}::jsonb)`);return await c.query(`INSERT INTO "${e}" (id, namespace, embedding, metadata) VALUES ${N.join(", ")} ${a}`,g),{mutationId:S()}};return{async deleteByIds(n){return n.length===0?{count:0,mutationId:S()}:(await $(),{count:(await c.query(`DELETE FROM "${e}" WHERE id = ANY($1::text[]) RETURNING id`,[[...n]])).length,mutationId:S()})},async describe(){await $();const[n]=await c.query(`SELECT count(*) AS count FROM "${e}"`);return{dimensions:o,vectorsCount:Number(n?.count??0)}},async getByIds(n){return n.length===0?[]:(await $(),(await c.query(`SELECT id, namespace, metadata, embedding::text AS embedding FROM "${e}" WHERE id = ANY($1::text[])`,[[...n]])).map(s=>({id:s.id,...s.metadata===null?{}:{metadata:s.metadata},...s.namespace===null?{}:{namespace:s.namespace},values:JSON.parse(s.embedding)})))},async insert(n){return O(n,"ON CONFLICT (id) DO NOTHING")},async query(n,a){const s=a?.topK??X;if(!Number.isInteger(s)||s<=0)throw new TypeError(`@lunora/hyperdrive: pgvector index "${m}" needs a positive integer \`topK\` — got ${String(s)}`);a?.filter!==void 0&&J(a.filter,m),await $();const g=a?.returnValues===!0,u=(a?.returnMetadata??"none")!=="none",N=[],i=d=>`$${String(N.push(d))}`,T=`embedding ${r} ${i(A(n))}::vector`,f=[];a?.namespace!==void 0&&f.push(`namespace = ${i(a.namespace)}`),a?.filter!==void 0&&Object.keys(a.filter).length>0&&f.push(`metadata @> ${i(JSON.stringify(a.filter))}::jsonb`);const h=["id","namespace",`${T} AS distance`];u&&h.push("metadata"),g&&h.push("embedding::text AS embedding");const L=f.length>0?`(SELECT * FROM "${e}" WHERE ${f.join(" AND ")})`:`"${e}"`,M=f.length>0?`WITH filtered AS MATERIALIZED ${L} SELECT ${h.join(", ")} FROM filtered ORDER BY ${T} LIMIT ${i(s)}`:`SELECT ${h.join(", ")} FROM "${e}" ORDER BY ${T} LIMIT ${i(s)}`,w=(await c.query(M,N)).map(d=>({id:d.id,...u&&d.metadata!==null&&d.metadata!==void 0?{metadata:d.metadata}:{},...d.namespace===null?{}:{namespace:d.namespace},score:l(Number(d.distance)),...g&&d.embedding!==void 0?{values:JSON.parse(d.embedding)}:{}}));return{count:w.length,matches:w}},async upsert(n){return O(n,"ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding, namespace = EXCLUDED.namespace, metadata = EXCLUDED.metadata")}}};export{H as createPgVectorIndex};
@@ -0,0 +1 @@
1
+ import{sql as t}from"drizzle-orm";const r="__id__",s="__vector__",o=e=>t`${t.identifier(e)}.${t.identifier(s)}`,m=e=>t`to_tsvector('simple', ${e})`,c=e=>t`to_tsquery('simple', ${e.map((n,i)=>i===e.length-1?`${n}:*`:n).join(" & ")})`,T=/duplicate key value violates unique constraint/iu,u="utf8mb4_0900_bin",a=e=>`${e} COLLATE ${u}`,E=(e,n)=>{if(n?.unique===!0)switch(e){case"bigint":case"boolean":case"date":case"number":case"timestamp":break;case"bytes":return"VARBINARY(768)";default:return a("VARCHAR(768)")}switch(e){case"bigint":return a("VARCHAR(64)");case"boolean":return"TINYINT";case"bytes":return"LONGBLOB";case"date":case"number":case"timestamp":return"DOUBLE";default:return a("LONGTEXT")}},l=/TEXT|BLOB/u,_={companionTypes:{autoincrementPrimaryKey:"BIGSERIAL PRIMARY KEY",integer:"INTEGER",key:"TEXT",real:"DOUBLE PRECISION",text:"TEXT"},columnType:e=>{switch(e){case"boolean":return"INTEGER";case"bytes":return"BYTEA";case"date":case"number":case"timestamp":return"DOUBLE PRECISION";default:return"TEXT"}},frameworkColumns:()=>[{name:"id",type:"TEXT PRIMARY KEY"},{name:"_creationTime",type:"DOUBLE PRECISION NOT NULL"}],isUniqueViolation:e=>{const{code:n}=e;return n==="23505"||e instanceof Error&&T.test(e.message)},maxTableColumns:1600,name:"postgres",supportsFts5:!1,nativeTextSearch:{createCompanion:(e,n)=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(e)} (${t.identifier(r)} ${t.raw(n)} PRIMARY KEY, ${t.identifier(s)} tsvector)`,createIndexes:e=>[t`CREATE INDEX IF NOT EXISTS ${t.identifier(`${e}__gin`)} ON ${t.identifier(e)} USING GIN (${t.identifier(s)})`],indexDocument:(e,n,i)=>t`INSERT INTO ${t.identifier(e)} (${t.identifier(r)}, ${t.identifier(s)}) VALUES (${n}, ${m(i)})`,matches:(e,n)=>t`${o(e)} @@ ${c(n)}`,rank:(e,n)=>t`ts_rank_cd(${o(e)}, ${c(n)})`},supportsReturning:!0,textPatternOperatorClass:"text_pattern_ops",tableExists:e=>t`SELECT table_name FROM information_schema.tables WHERE table_schema = ANY (current_schemas(false)) AND table_name = ${e}`},I={affectedRows:e=>e.rowsAffected,companionTypes:{autoincrementPrimaryKey:"BIGINT AUTO_INCREMENT PRIMARY KEY",integer:"INTEGER",key:a("VARCHAR(768)"),real:"DOUBLE",text:a("LONGTEXT")},columnType:E,frameworkColumns:()=>[{name:"id",type:`${a("VARCHAR(768)")} PRIMARY KEY`},{name:"_creationTime",type:"DOUBLE NOT NULL"}],indexKeyPrefix:e=>l.test(E(e))?191:void 0,isUniqueViolation:e=>{const n=e;return n.errno===1062||n.code==="ER_DUP_ENTRY"},maxTableColumns:4096,name:"mysql",supportsFts5:!1,supportsReturning:!1,tableExists:e=>t`SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ${e}`};export{I as mysqlDialect,_ as postgresDialect};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/hyperdrive",
3
- "version": "1.0.0-alpha.107",
3
+ "version": "1.0.0-alpha.108",
4
4
  "description": "Bring-your-own Postgres/MySQL for Lunora via Cloudflare Hyperdrive: a driver-agnostic, action-only ctx.sql",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,10 +50,10 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/errors": "1.0.0-alpha.30",
54
- "@lunora/platform": "1.0.0-alpha.25",
55
- "@lunora/shard-engine": "1.0.0-alpha.54",
56
- "@lunora/sql-store": "1.0.0-alpha.107",
53
+ "@lunora/errors": "1.0.0-alpha.32",
54
+ "@lunora/platform": "1.0.0-alpha.26",
55
+ "@lunora/shard-engine": "1.0.0-alpha.56",
56
+ "@lunora/sql-store": "1.0.0-alpha.109",
57
57
  "drizzle-orm": "^0.45.2"
58
58
  },
59
59
  "peerDependencies": {
@@ -1 +0,0 @@
1
- const L=t=>/^[A-Z_]\w*$/i.test(t);const M=new Set(["42P06","42P07","23505","42710"]),x=t=>typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&M.has(t.code),j=5,C="__vec_",R="__ann_",b={cosine:{operator:"<=>",operatorClass:"vector_cosine_ops",score:t=>1-t},"dot-product":{operator:"<#>",operatorClass:"vector_ip_ops",score:t=>t},euclidean:{operator:"<->",operatorClass:"vector_l2_ops",score:t=>t}},F=63,_=F-C.length-R.length-Math.max(...Object.values(b).map(t=>t.operatorClass.length)),A=t=>`[${t.join(",")}]`,X=(t,m)=>{const o=(e,r)=>{throw new TypeError(`@lunora/hyperdrive: pgvector index "${m}" supports equality metadata filters only, but "${r}" ${e}. Pre-compute it into an equality-shaped metadata field, or keep this index on Vectorize.`)},E=(e,r)=>{(e===void 0||typeof e=="function"||typeof e=="symbol")&&o(`has a value at "${r}" that JSON cannot represent, which would widen the filter to match every row`,r),typeof e=="number"&&!Number.isFinite(e)&&o(`has a non-finite number at "${r}", which JSON turns into null`,r),typeof e=="bigint"&&o(`has a bigint at "${r}", which JSON cannot serialise`,r)},d=(e,r)=>{if(E(e,r),Array.isArray(e)){for(const[p,l]of e.entries())d(l,`${r}[${String(p)}]`);return}if(!(typeof e!="object"||e===null))for(const[p,l]of Object.entries(e))p.startsWith("$")&&o("uses a comparison operator",r),d(l,`${r}.${p}`)};for(const[e,r]of Object.entries(t))e.startsWith("$")&&o("uses a comparison operator",e),e.includes(".")&&o("uses Vectorize's dot-addressed nested syntax, which JSONB containment cannot express",e),d(r,e)},U=t=>{if(!L(t))throw new TypeError(`@lunora/hyperdrive: pgvector \`name\` must be a bare SQL identifier (letters, digits, underscore; not starting with a digit) — got "${t}"`);if(t.length>_)throw new TypeError(`@lunora/hyperdrive: pgvector \`name\` must be at most ${String(_)} characters — got "${t}" (${String(t.length)}). Postgres truncates identifiers at 63 bytes and this index derives longer names from it.`);return t},H=t=>{const{client:m,dimensions:o,metric:E="cosine",name:d}=t,e=`${C}${U(d)}`;if(!Object.hasOwn(b,E))throw new TypeError(`@lunora/hyperdrive: pgvector index "${d}" got an unknown metric "${E}" — expected cosine, euclidean, or dot-product`);const{operator:r,operatorClass:p,score:l}=b[E];if(!Number.isInteger(o)||o<=0)throw new TypeError(`@lunora/hyperdrive: pgvector index "${d}" needs a positive integer \`dimensions\` — got ${String(o)}`);if(o>2e3)throw new TypeError(`@lunora/hyperdrive: pgvector index "${d}" declares ${String(o)} dimensions, over the HNSW limit of ${String(2e3)}. Reduce the embedding width (Vectorize itself tops out at 1536), or keep this index on Vectorize.`);let y=0;const h=()=>(y+=1,`${e}:${String(y)}`);let I;const $=async()=>(I??=(async()=>{for(const n of["CREATE EXTENSION IF NOT EXISTS vector",`CREATE TABLE IF NOT EXISTS "${e}" (id text PRIMARY KEY, namespace text, embedding vector(${String(o)}) NOT NULL, metadata jsonb)`,`CREATE INDEX IF NOT EXISTS "${e}${R}${p}" ON "${e}" USING hnsw (embedding ${p})`,`CREATE INDEX IF NOT EXISTS "${e}__ns" ON "${e}" (namespace)`,`CREATE INDEX IF NOT EXISTS "${e}__meta" ON "${e}" USING gin (metadata)`])try{await m.query(n)}catch(a){if(!x(a))throw a}})().catch(n=>{throw I=void 0,n}),I),w=async(n,a)=>{if(n.length===0)return{mutationId:h()};await $();const s=[...new Map(n.map(i=>[i.id,i])).values()],g=[],u=i=>`$${String(g.push(i))}`,S=s.map(i=>`(${u(i.id)}, ${u(i.namespace??null)}, ${u(A(i.values))}::vector, ${u(i.metadata===void 0?null:JSON.stringify(i.metadata))}::jsonb)`);return await m.query(`INSERT INTO "${e}" (id, namespace, embedding, metadata) VALUES ${S.join(", ")} ${a}`,g),{mutationId:h()}};return{async deleteByIds(n){return n.length===0?{count:0,mutationId:h()}:(await $(),{count:(await m.query(`DELETE FROM "${e}" WHERE id = ANY($1::text[]) RETURNING id`,[[...n]])).length,mutationId:h()})},async describe(){await $();const[n]=await m.query(`SELECT count(*) AS count FROM "${e}"`);return{dimensions:o,vectorsCount:Number(n?.count??0)}},async getByIds(n){return n.length===0?[]:(await $(),(await m.query(`SELECT id, namespace, metadata, embedding::text AS embedding FROM "${e}" WHERE id = ANY($1::text[])`,[[...n]])).map(s=>({id:s.id,...s.metadata===null?{}:{metadata:s.metadata},...s.namespace===null?{}:{namespace:s.namespace},values:JSON.parse(s.embedding)})))},async insert(n){return w(n,"ON CONFLICT (id) DO NOTHING")},async query(n,a){const s=a?.topK??j;if(!Number.isInteger(s)||s<=0)throw new TypeError(`@lunora/hyperdrive: pgvector index "${d}" needs a positive integer \`topK\` — got ${String(s)}`);a?.filter!==void 0&&Object.keys(a.filter).length>0&&X(a.filter,d),await $();const g=a?.returnValues===!0,u=(a?.returnMetadata??"none")!=="none",S=[],i=c=>`$${String(S.push(c))}`,T=`embedding ${r} ${i(A(n))}::vector`,f=[];a?.namespace!==void 0&&f.push(`namespace = ${i(a.namespace)}`),a?.filter!==void 0&&Object.keys(a.filter).length>0&&f.push(`metadata @> ${i(JSON.stringify(a.filter))}::jsonb`);const N=["id","namespace",`${T} AS distance`];u&&N.push("metadata"),g&&N.push("embedding::text AS embedding");const D=f.length>0?`(SELECT * FROM "${e}" WHERE ${f.join(" AND ")})`:`"${e}"`,v=f.length>0?`WITH filtered AS MATERIALIZED ${D} SELECT ${N.join(", ")} FROM filtered ORDER BY ${T} LIMIT ${i(s)}`:`SELECT ${N.join(", ")} FROM "${e}" ORDER BY ${T} LIMIT ${i(s)}`,O=(await m.query(v,S)).map(c=>({id:c.id,...u&&c.metadata!==null&&c.metadata!==void 0?{metadata:c.metadata}:{},...c.namespace===null?{}:{namespace:c.namespace},score:l(Number(c.distance)),...g&&c.embedding!==void 0?{values:JSON.parse(c.embedding)}:{}}));return{count:O.length,matches:O}},async upsert(n){return w(n,"ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding, namespace = EXCLUDED.namespace, metadata = EXCLUDED.metadata")}}};export{H as createPgVectorIndex};
@@ -1 +0,0 @@
1
- import{sql as t}from"drizzle-orm";const r="__id__",s="__vector__",o=e=>t`${t.identifier(e)}.${t.identifier(s)}`,T=e=>t`to_tsvector('simple', ${e})`,E=e=>t`to_tsquery('simple', ${e.map((n,i)=>i===e.length-1?`${n}:*`:n).join(" & ")})`,m=/duplicate key value violates unique constraint/iu,l="utf8mb4_0900_bin",a=e=>`${e} COLLATE ${l}`,c=e=>{switch(e){case"bigint":return a("VARCHAR(64)");case"boolean":return"TINYINT";case"bytes":return"LONGBLOB";case"date":case"number":case"timestamp":return"DOUBLE";default:return a("LONGTEXT")}},u=/TEXT|BLOB/u,_={companionTypes:{autoincrementPrimaryKey:"BIGSERIAL PRIMARY KEY",integer:"INTEGER",key:"TEXT",real:"DOUBLE PRECISION",text:"TEXT"},columnType:e=>{switch(e){case"boolean":return"INTEGER";case"bytes":return"BYTEA";case"date":case"number":case"timestamp":return"DOUBLE PRECISION";default:return"TEXT"}},frameworkColumns:()=>[{name:"id",type:"TEXT PRIMARY KEY"},{name:"_creationTime",type:"DOUBLE PRECISION NOT NULL"}],isUniqueViolation:e=>{const{code:n}=e;return n==="23505"||e instanceof Error&&m.test(e.message)},maxTableColumns:1600,name:"postgres",supportsFts5:!1,nativeTextSearch:{createCompanion:(e,n)=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(e)} (${t.identifier(r)} ${t.raw(n)} PRIMARY KEY, ${t.identifier(s)} tsvector)`,createIndexes:e=>[t`CREATE INDEX IF NOT EXISTS ${t.identifier(`${e}__gin`)} ON ${t.identifier(e)} USING GIN (${t.identifier(s)})`],indexDocument:(e,n,i)=>t`INSERT INTO ${t.identifier(e)} (${t.identifier(r)}, ${t.identifier(s)}) VALUES (${n}, ${T(i)})`,matches:(e,n)=>t`${o(e)} @@ ${E(n)}`,rank:(e,n)=>t`ts_rank_cd(${o(e)}, ${E(n)})`},supportsReturning:!0,textPatternOperatorClass:"text_pattern_ops",tableExists:e=>t`SELECT table_name FROM information_schema.tables WHERE table_schema = ANY (current_schemas(false)) AND table_name = ${e}`},I={affectedRows:e=>e.rowsAffected,companionTypes:{autoincrementPrimaryKey:"BIGINT AUTO_INCREMENT PRIMARY KEY",integer:"INTEGER",key:a("VARCHAR(768)"),real:"DOUBLE",text:a("LONGTEXT")},columnType:c,frameworkColumns:()=>[{name:"id",type:`${a("VARCHAR(768)")} PRIMARY KEY`},{name:"_creationTime",type:"DOUBLE NOT NULL"}],indexKeyPrefix:e=>u.test(c(e))?191:void 0,isUniqueViolation:e=>{const n=e;return n.errno===1062||n.code==="ER_DUP_ENTRY"},maxTableColumns:4096,name:"mysql",supportsFts5:!1,supportsReturning:!1,tableExists:e=>t`SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ${e}`};export{I as mysqlDialect,_ as postgresDialect};