import {
  Clock,
  EffectProto,
  ParentSpan,
  Reference,
  Scope,
  Service,
  TracerTimingEnabled,
  add,
  addFinalizer1 as addFinalizer,
  close,
  constUndefined,
  effect,
  endSpan,
  ensuring,
  evaluate,
  exit,
  failCauseUnsafe,
  flatMap1 as flatMap,
  flow,
  fnUntraced1 as fnUntraced,
  fromQueue,
  gen1 as gen,
  get,
  getOption,
  hasProperty,
  hash,
  identifier,
  isSuccess1 as isSuccess,
  make3 as make,
  make6 as make2,
  makeSpanScoped,
  makeSpanUnsafe,
  map6 as map,
  match,
  offerUnsafe,
  onExit1 as onExit,
  orDie,
  provide,
  provideService,
  provideServices,
  runForkWith,
  runIn,
  scoped,
  serviceOption,
  services,
  servicesWith1 as servicesWith,
  succeed4 as succeed,
  suspend1 as suspend,
  sync1 as sync,
  tap,
  uninterruptibleMask1 as uninterruptibleMask,
  unwrap1 as unwrap,
  useSpan,
  void_1 as void_,
  withFiber1 as withFiber
} from "./index-w9j14fjm.js";

// ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect-smol+effect@8881a9b/node_modules/effect/dist/unstable/reactivity/Reactivity.js
class Reactivity extends (/* @__PURE__ */ Service()("effect/reactivity/Reactivity")) {
}
var make3 = /* @__PURE__ */ sync(() => {
  const handlers = new Map;
  const invalidateUnsafe = (keys) => {
    keysToHashes(keys, (hash2) => {
      const set = handlers.get(hash2);
      if (set === undefined)
        return;
      set.forEach((run) => run());
    });
  };
  const invalidate = (keys) => servicesWith((services2) => {
    const pending = services2.mapUnsafe.get(PendingInvalidation.key);
    if (pending) {
      keysToHashes(keys, (hash2) => {
        pending.add(hash2);
      });
    } else {
      invalidateUnsafe(keys);
    }
    return void_;
  });
  const mutation = (keys, effect2) => tap(effect2, invalidate(keys));
  const registerUnsafe = (keys, handler) => {
    const resolvedKeys = [];
    keysToHashes(keys, (hash2) => {
      resolvedKeys.push(hash2);
      let set = handlers.get(hash2);
      if (set === undefined) {
        set = new Set;
        handlers.set(hash2, set);
      }
      set.add(handler);
    });
    return () => {
      for (let i = 0;i < resolvedKeys.length; i++) {
        const set = handlers.get(resolvedKeys[i]);
        set.delete(handler);
        if (set.size === 0) {
          handlers.delete(resolvedKeys[i]);
        }
      }
    };
  };
  const query = (keys, effect2) => gen(function* () {
    const services2 = yield* services();
    const scope = get(services2, Scope);
    const results = yield* make2();
    const runFork = flow(runForkWith(services2), runIn(scope));
    let running = false;
    let pending = false;
    const handleExit = (exit2) => {
      if (exit2._tag === "Failure") {
        failCauseUnsafe(results, exit2.cause);
      } else {
        offerUnsafe(results, exit2.value);
      }
      if (pending) {
        pending = false;
        runFork(effect2).addObserver(handleExit);
      } else {
        running = false;
      }
    };
    function run() {
      if (running) {
        pending = true;
        return;
      }
      running = true;
      runFork(effect2).addObserver(handleExit);
    }
    const cancel = registerUnsafe(keys, run);
    yield* addFinalizer(scope, sync(cancel));
    run();
    return results;
  });
  const stream = (tables, effect2) => query(tables, effect2).pipe(map(fromQueue), unwrap);
  const withBatch = (effect2) => suspend(() => {
    const pending = new Set;
    return effect2.pipe(provideService(PendingInvalidation, pending), onExit((_) => sync(() => {
      pending.forEach((hash2) => {
        const set = handlers.get(hash2);
        if (set === undefined)
          return;
        set.forEach((run) => run());
      });
    })));
  });
  return Reactivity.of({
    mutation,
    query,
    stream,
    invalidateUnsafe,
    invalidate,
    registerUnsafe,
    withBatch
  });
});

class PendingInvalidation extends (/* @__PURE__ */ Service()("effect/reactivity/Reactivity/PendingInvalidation")) {
}
var layer = /* @__PURE__ */ effect(Reactivity)(make3);
function stringOrHash(u) {
  switch (typeof u) {
    case "string":
    case "number":
    case "bigint":
    case "boolean":
      return String(u);
    default:
      return hash(u);
  }
}
var keysToHashes = (keys, f) => {
  if (Array.isArray(keys)) {
    for (let i = 0;i < keys.length; i++) {
      f(stringOrHash(keys[i]));
    }
    return;
  }
  for (const key in keys) {
    f(key);
    const ids = keys[key];
    for (let i = 0;i < ids.length; i++) {
      f(`${key}:${stringOrHash(ids[i])}`);
    }
  }
};

// ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect-smol+effect@8881a9b/node_modules/effect/dist/unstable/sql/Statement.js
var FragmentTypeId = "~effect/sql/Fragment";
var fragment = (segments) => ({
  [FragmentTypeId]: FragmentTypeId,
  segments
});
var CurrentTransformer = /* @__PURE__ */ Reference("effect/sql/CurrentTransformer", {
  defaultValue: constUndefined
});
var isFragment = (u) => hasProperty(u, FragmentTypeId);
var literal = (value, params) => ({
  _tag: "Literal",
  value,
  params
});
var identifier2 = (value) => ({
  _tag: "Identifier",
  value
});
var parameter = (value) => ({
  _tag: "Parameter",
  value
});
var arrayHelper = (value) => ({
  _tag: "ArrayHelper",
  value
});
var RecordInsertHelperProto = {
  _tag: "RecordInsertHelper",
  returning(sql) {
    const self = Object.create(Object.getPrototypeOf(this));
    Object.assign(self, this, {
      returningIdentifier: sql
    });
    return self;
  }
};
var recordInsertHelper = (value) => Object.assign(Object.create(RecordInsertHelperProto), {
  value,
  returningIdentifier: undefined
});
var RecordUpdateHelperProto = {
  ...RecordInsertHelperProto,
  _tag: "RecordUpdateHelper"
};
var recordUpdateHelper = (value, alias) => Object.assign(Object.create(RecordUpdateHelperProto), {
  value,
  alias,
  returningIdentifier: undefined
});
var RecordUpdateHelperSingleProto = {
  ...RecordInsertHelperProto,
  _tag: "RecordUpdateHelperSingle"
};
var recordUpdateHelperSingle = (value, omit) => Object.assign(Object.create(RecordUpdateHelperSingleProto), {
  value,
  omit,
  returningIdentifier: undefined
});
var make4 = (acquirer, compiler, spanAttributes, transformRows) => {
  const cache = transformRows === undefined ? constructorCache.noTransforms : constructorCache.transforms;
  if (cache.has(acquirer)) {
    return cache.get(acquirer);
  }
  const self = Object.assign(function sql(strings, ...args) {
    if (typeof strings === "string") {
      return identifier2(strings);
    } else if (Array.isArray(strings) && "raw" in strings) {
      return statement(acquirer, compiler, strings, args, spanAttributes, transformRows);
    }
    throw "absurd";
  }, {
    unsafe(sql, params) {
      return makeUnsafe([literal(sql, params)], acquirer, compiler, spanAttributes, transformRows);
    },
    literal(sql) {
      return fragment([literal(sql)]);
    },
    in: in_,
    insert(value) {
      return recordInsertHelper(Array.isArray(value) ? value : [value]);
    },
    update(value, omit) {
      return recordUpdateHelperSingle(value, omit ?? []);
    },
    updateValues(value, alias) {
      return recordUpdateHelper(value, alias);
    },
    and,
    or,
    csv,
    join,
    onDialect(options) {
      return options[compiler.dialect]();
    },
    onDialectOrElse(options) {
      return options[compiler.dialect] !== undefined ? options[compiler.dialect]() : options.orElse();
    }
  });
  cache.set(acquirer, self);
  return self;
};
var constructorCache = {
  transforms: /* @__PURE__ */ new WeakMap,
  noTransforms: /* @__PURE__ */ new WeakMap
};
var statement = (acquirer, compiler, strings, args, spanAttributes, transformRows) => {
  const segments = strings[0].length > 0 ? [literal(strings[0])] : [];
  for (let i = 0;i < args.length; i++) {
    const arg = args[i];
    if (isFragment(arg)) {
      segments.push(...arg.segments);
    } else if (isSegment(arg)) {
      segments.push(arg);
    } else {
      segments.push(parameter(arg));
    }
    if (strings[i + 1].length > 0) {
      segments.push(literal(strings[i + 1]));
    }
  }
  return makeUnsafe(segments, acquirer, compiler, spanAttributes, transformRows);
};
function join(lit, addParens = true, fallback = "") {
  const literalStatement = literal(lit);
  const fallbackFragment = fragment([literal(fallback)]);
  return (clauses) => {
    if (clauses.length === 0) {
      return fallbackFragment;
    } else if (clauses.length === 1) {
      return fragment(convertLiteralOrFragment(clauses[0]));
    }
    const segments = [];
    if (addParens) {
      segments.push(literal("("));
    }
    segments.push.apply(segments, convertLiteralOrFragment(clauses[0]));
    for (let i = 1;i < clauses.length; i++) {
      segments.push(literalStatement);
      segments.push.apply(segments, convertLiteralOrFragment(clauses[i]));
    }
    if (addParens) {
      segments.push(literal(")"));
    }
    return fragment(segments);
  };
}
var and = /* @__PURE__ */ join(" AND ", true, "1=1");
var or = /* @__PURE__ */ join(" OR ", true, "1=1");
var csv = function(...args) {
  if (args[args.length - 1].length === 0) {
    return emptyFragment;
  }
  if (args.length === 1) {
    return csvRaw(args[0]);
  }
  return fragment([literal(`${args[0]} `), ...csvRaw(args[1]).segments]);
};
var csvRaw = /* @__PURE__ */ join(",", false);
var emptyFragment = /* @__PURE__ */ fragment([/* @__PURE__ */ literal("")]);
var makeCompiler = (options) => {
  const self = Object.create(CompilerProto);
  self.options = options;
  self.dialect = options.dialect;
  self.disableTransforms = false;
  return self;
};
var statementCacheSymbol = /* @__PURE__ */ Symbol.for("effect/unstable/sql/Statement/statementCache");
var statementCacheNoTransformSymbol = /* @__PURE__ */ Symbol.for("effect/unstable/sql/Statement/statementCacheNoTransform");
var CompilerProto = {
  compile(statement2, withoutTransform = false, placeholderOverride) {
    const opts = this.options;
    withoutTransform = withoutTransform || this.disableTransforms;
    const cacheSymbol = withoutTransform ? statementCacheNoTransformSymbol : statementCacheSymbol;
    if (cacheSymbol in statement2) {
      return statement2[cacheSymbol];
    }
    const segments = statement2.segments;
    const len = segments.length;
    let sql = "";
    const binds = [];
    let placeholderCount = 0;
    const placeholder = placeholderOverride ?? ((u) => opts.placeholder(++placeholderCount, u));
    const placeholderNoIncrement = (u) => opts.placeholder(placeholderCount, u);
    const placeholders = makePlaceholdersArray(placeholder);
    for (let i = 0;i < len; i++) {
      const segment = segments[i];
      switch (segment._tag) {
        case "Literal": {
          sql += segment.value;
          if (segment.params) {
            binds.push.apply(binds, segment.params);
          }
          break;
        }
        case "Identifier": {
          sql += opts.onIdentifier(segment.value, withoutTransform);
          break;
        }
        case "Parameter": {
          sql += placeholder(segment.value);
          binds.push(segment.value);
          break;
        }
        case "ArrayHelper": {
          sql += `(${placeholders(segment.value)})`;
          binds.push.apply(binds, segment.value);
          break;
        }
        case "RecordInsertHelper": {
          const keys = Object.keys(segment.value[0]);
          if (opts.onInsert) {
            const values = new Array(segment.value.length);
            let placeholders2 = "";
            for (let i2 = 0;i2 < segment.value.length; i2++) {
              const row = new Array(keys.length);
              values[i2] = row;
              placeholders2 += i2 === 0 ? "(" : ",(";
              for (let j = 0;j < keys.length; j++) {
                const key = keys[j];
                const value = segment.value[i2][key];
                const primitive = extractPrimitive(value, opts.onCustom, placeholderNoIncrement, withoutTransform);
                row[j] = primitive;
                placeholders2 += j === 0 ? placeholder(value) : `,${placeholder(value)}`;
              }
              placeholders2 += ")";
            }
            const [s, b] = opts.onInsert(keys.map((_) => opts.onIdentifier(_, withoutTransform)), placeholders2, values, typeof segment.returningIdentifier === "string" ? [segment.returningIdentifier, []] : segment.returningIdentifier ? this.compile(segment.returningIdentifier, withoutTransform, placeholder) : undefined);
            sql += s;
            binds.push.apply(binds, b);
          } else {
            let placeholders2 = "";
            for (let i2 = 0;i2 < segment.value.length; i2++) {
              placeholders2 += i2 === 0 ? "(" : ",(";
              for (let j = 0;j < keys.length; j++) {
                const value = segment.value[i2][keys[j]];
                const primitive = extractPrimitive(value, opts.onCustom, placeholderNoIncrement, withoutTransform);
                binds.push(primitive);
                placeholders2 += j === 0 ? placeholder(value) : `,${placeholder(value)}`;
              }
              placeholders2 += ")";
            }
            sql += `${generateColumns(keys, opts.onIdentifier, withoutTransform)} VALUES ${placeholders2}`;
            if (typeof segment.returningIdentifier === "string") {
              sql += ` RETURNING ${segment.returningIdentifier}`;
            } else if (segment.returningIdentifier) {
              sql += " RETURNING ";
              const [s, b] = this.compile(segment.returningIdentifier, withoutTransform, placeholder);
              sql += s;
              binds.push.apply(binds, b);
            }
          }
          break;
        }
        case "RecordUpdateHelperSingle": {
          let keys = Object.keys(segment.value);
          if (segment.omit.length > 0) {
            keys = keys.filter((key) => !segment.omit.includes(key));
          }
          if (opts.onRecordUpdateSingle) {
            const [s, b] = opts.onRecordUpdateSingle(keys.map((_) => opts.onIdentifier(_, withoutTransform)), keys.map((key) => extractPrimitive(segment.value[key], opts.onCustom, placeholderNoIncrement, withoutTransform)), typeof segment.returningIdentifier === "string" ? [segment.returningIdentifier, []] : segment.returningIdentifier ? this.compile(segment.returningIdentifier, withoutTransform, placeholder) : undefined);
            sql += s;
            binds.push.apply(binds, b);
          } else {
            for (let i2 = 0, len2 = keys.length;i2 < len2; i2++) {
              const column = opts.onIdentifier(keys[i2], withoutTransform);
              if (i2 === 0) {
                sql += `${column} = ${placeholder(segment.value[keys[i2]])}`;
              } else {
                sql += `, ${column} = ${placeholder(segment.value[keys[i2]])}`;
              }
              binds.push(extractPrimitive(segment.value[keys[i2]], opts.onCustom, placeholderNoIncrement, withoutTransform));
            }
            if (typeof segment.returningIdentifier === "string") {
              if (this.dialect === "mssql") {
                sql += ` OUTPUT ${segment.returningIdentifier === "*" ? "INSERTED.*" : segment.returningIdentifier}`;
              } else {
                sql += ` RETURNING ${segment.returningIdentifier}`;
              }
            } else if (segment.returningIdentifier) {
              sql += this.dialect === "mssql" ? " OUTPUT " : " RETURNING ";
              const [s, b] = this.compile(segment.returningIdentifier, withoutTransform, placeholder);
              sql += s;
              binds.push.apply(binds, b);
            }
          }
          break;
        }
        case "RecordUpdateHelper": {
          const keys = Object.keys(segment.value[0]);
          const values = new Array(segment.value.length);
          let placeholders2 = "";
          for (let i2 = 0;i2 < segment.value.length; i2++) {
            const row = new Array(keys.length);
            values[i2] = row;
            placeholders2 += i2 === 0 ? "(" : ",(";
            for (let j = 0;j < keys.length; j++) {
              const key = keys[j];
              const value = segment.value[i2][key];
              row[j] = extractPrimitive(value, opts.onCustom, placeholderNoIncrement, withoutTransform);
              placeholders2 += j === 0 ? placeholder(value) : `,${placeholder(value)}`;
            }
            placeholders2 += ")";
          }
          const [s, b] = opts.onRecordUpdate(placeholders2, segment.alias, generateColumns(keys, opts.onIdentifier, withoutTransform), values, typeof segment.returningIdentifier === "string" ? [segment.returningIdentifier, []] : segment.returningIdentifier ? this.compile(segment.returningIdentifier, withoutTransform, placeholder) : undefined);
          sql += s;
          binds.push.apply(binds, b);
          break;
        }
        case "Custom": {
          const [s, b] = opts.onCustom(segment, placeholder, withoutTransform);
          sql += s;
          binds.push.apply(binds, b);
          break;
        }
      }
    }
    const result = [sql, binds];
    if (placeholderOverride !== undefined) {
      return result;
    }
    return statement2[cacheSymbol] = result;
  },
  get withoutTransform() {
    const self = Object.create(CompilerProto);
    Object.assign(self, this, {
      disableTransforms: true
    });
    return self;
  }
};
var makeCompilerSqlite = (transform) => makeCompiler({
  dialect: "sqlite",
  placeholder(_) {
    return "?";
  },
  onIdentifier: transform ? function(value, withoutTransform) {
    return withoutTransform ? escapeSqlite(value) : escapeSqlite(transform(value));
  } : escapeSqlite,
  onRecordUpdate() {
    return ["", []];
  },
  onCustom() {
    return ["", []];
  }
});
function defaultEscape(c) {
  const re = new RegExp(c, "g");
  const double = c + c;
  const dot = c + "." + c;
  return function(str) {
    return c + str.replace(re, double).replace(/\./g, dot) + c;
  };
}
var defaultTransforms = (transformer, nested = true) => {
  const transformValue = (value) => {
    if (Array.isArray(value)) {
      if (value.length === 0 || value[0].constructor !== Object) {
        return value;
      }
      return array(value);
    } else if (value?.constructor === Object) {
      return transformObject(value);
    }
    return value;
  };
  const transformObject = (obj) => {
    const newObj = {};
    for (const key in obj) {
      newObj[transformer(key)] = transformValue(obj[key]);
    }
    return newObj;
  };
  const transformArrayNested = (rows) => {
    const newRows = new Array(rows.length);
    for (let i = 0, len = rows.length;i < len; i++) {
      const row = rows[i];
      if (Array.isArray(row)) {
        newRows[i] = transformArrayNested(row);
      } else {
        const obj = {};
        for (const key in row) {
          obj[transformer(key)] = transformValue(row[key]);
        }
        newRows[i] = obj;
      }
    }
    return newRows;
  };
  const transformArray = (rows) => {
    const newRows = new Array(rows.length);
    for (let i = 0, len = rows.length;i < len; i++) {
      const row = rows[i];
      if (Array.isArray(row)) {
        newRows[i] = transformArray(row);
      } else {
        const obj = {};
        for (const key in row) {
          obj[transformer(key)] = row[key];
        }
        newRows[i] = obj;
      }
    }
    return newRows;
  };
  const array = nested ? transformArrayNested : transformArray;
  return {
    value: transformValue,
    object: transformObject,
    array
  };
};
var ATTR_DB_OPERATION_NAME = "db.operation.name";
var ATTR_DB_QUERY_TEXT = "db.query.text";
var makeUnsafe = (segments, acquirer, compiler, spanAttributes, transformRows) => {
  const self = Object.create(StatementProto);
  self.segments = segments;
  self.acquirer = acquirer;
  self.compiler = compiler;
  self.spanAttributes = spanAttributes;
  self.transformRows = transformRows;
  return self;
};
var StatementProto = {
  ...EffectProto,
  [identifier]: "Statement",
  [FragmentTypeId]: FragmentTypeId,
  withConnection(operation, f, withoutTransform = false) {
    return useSpan("sql.execute", {
      kind: "client"
    }, (span) => this.withConnectionSpan(operation, f, withoutTransform, span));
  },
  withConnectionSpan(operation, f, withoutTransform, span) {
    return withStatement(this, span, (statement2) => {
      const [sql, params] = statement2.compile(withoutTransform);
      for (const [key, value] of this.spanAttributes) {
        span.attribute(key, value);
      }
      span.attribute(ATTR_DB_OPERATION_NAME, operation);
      span.attribute(ATTR_DB_QUERY_TEXT, sql);
      return scoped(flatMap(this.acquirer, (_) => f(_, sql, params)));
    });
  },
  get withoutTransform() {
    return this.withConnection("executeWithoutTransform", (connection, sql, params) => connection.execute(sql, params, undefined), true);
  },
  get raw() {
    return this.withConnection("executeRaw", (connection, sql, params) => connection.executeRaw(sql, params), true);
  },
  get stream() {
    const self = this;
    return unwrap(flatMap(makeSpanScoped("sql.execute", {
      kind: "client"
    }), (span) => withStatement(self, span, (statement2) => {
      const [sql, params] = statement2.compile();
      for (const [key, value] of self.spanAttributes) {
        span.attribute(key, value);
      }
      span.attribute(ATTR_DB_OPERATION_NAME, "executeStream");
      span.attribute(ATTR_DB_QUERY_TEXT, sql);
      return map(self.acquirer, (_) => _.executeStream(sql, params, self.transformRows));
    })));
  },
  get values() {
    return this.withConnection("executeValues", (connection, sql, params) => connection.executeValues(sql, params));
  },
  get unprepared() {
    const self = this;
    return self.withConnection("executeUnprepared", (connection, sql, params) => connection.executeUnprepared(sql, params, self.transformRows));
  },
  compile(withoutTransform) {
    return this.compiler.compile(this, withoutTransform ?? false);
  },
  [evaluate](fiber) {
    const span = makeSpanUnsafe(fiber, "sql.execute", {
      kind: "client"
    });
    const clock = fiber.getRef(Clock);
    const timingEnabled = fiber.getRef(TracerTimingEnabled);
    return onExit(this.withConnectionSpan("execute", (connection, sql, params) => connection.execute(sql, params, this.transformRows), false, span), (exit2) => endSpan(span, exit2, clock, timingEnabled));
  },
  toJSON() {
    const [sql, params] = this.compile();
    return {
      _id: "Statement",
      segments: this.segments,
      sql,
      params
    };
  }
};
var withStatement = (self, span, f) => withFiber((fiber) => {
  const transform = fiber.getRef(CurrentTransformer);
  if (transform === undefined) {
    return f(self);
  }
  return flatMap(transform(self, make4(self.acquirer, self.compiler, self.spanAttributes, self.transformRows), fiber, span), f);
});
var isSegment = (u) => {
  if (!hasProperty(u, "_tag")) {
    return false;
  }
  switch (u._tag) {
    case "Literal":
    case "Parameter":
    case "ArrayHelper":
    case "RecordInsertHelper":
    case "RecordUpdateHelper":
    case "RecordUpdateHelperSingle":
    case "Identifier":
    case "Custom":
      return true;
    default:
      return false;
  }
};
function convertLiteralOrFragment(clause) {
  if (typeof clause === "string") {
    return [literal(clause)];
  }
  return clause.segments;
}
var makePlaceholdersArray = (evaluate2) => (values) => {
  if (values.length === 0) {
    return "";
  }
  let result = evaluate2(values[0]);
  for (let i = 1;i < values.length; i++) {
    result += `,${evaluate2(values[i])}`;
  }
  return result;
};
var generateColumns = (keys, escape, withoutTransform) => {
  if (keys.length === 0) {
    return "()";
  }
  let str = `(${escape(keys[0], withoutTransform)}`;
  for (let i = 1;i < keys.length; i++) {
    str += `,${escape(keys[i], withoutTransform)}`;
  }
  return str + ")";
};
var extractPrimitive = (value, onCustom, placeholder, withoutTransform) => {
  if (value === undefined) {
    return null;
  } else if (isFragment(value)) {
    const head = value.segments[0];
    if (head._tag === "Custom") {
      const compiled = onCustom(head, placeholder, withoutTransform);
      return compiled[1][0] ?? null;
    } else if (head._tag === "Parameter") {
      return head.value;
    }
    return null;
  }
  return value;
};
var escapeSqlite = /* @__PURE__ */ defaultEscape('"');
function in_() {
  if (arguments.length === 1) {
    return arrayHelper(arguments[0]);
  }
  const column = arguments[0];
  const values = arguments[1];
  return values.length === 0 ? neverFragment : fragment([identifier2(column), literal(" IN "), arrayHelper(values)]);
}
var neverFragment = /* @__PURE__ */ fragment([/* @__PURE__ */ literal("1=0")]);

// ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect-smol+effect@8881a9b/node_modules/effect/dist/unstable/sql/SqlClient.js
var TypeId = "~effect/sql/SqlClient";
var SqlClient = /* @__PURE__ */ Service("effect/sql/SqlClient");
var make5 = /* @__PURE__ */ fnUntraced(function* (options) {
  const getConnection = flatMap(serviceOption(TransactionConnection), match({
    onNone: () => options.acquirer,
    onSome: ([conn]) => succeed(conn)
  }));
  const beginTransaction = options.beginTransaction ?? "BEGIN";
  const commit = options.commit ?? "COMMIT";
  const savepoint = options.savepoint ?? ((name) => `SAVEPOINT ${name}`);
  const rollback = options.rollback ?? "ROLLBACK";
  const rollbackSavepoint = options.rollbackSavepoint ?? ((name) => `ROLLBACK TO SAVEPOINT ${name}`);
  const transactionAcquirer = options.transactionAcquirer ?? options.acquirer;
  const withTransaction = makeWithTransaction({
    transactionService: TransactionConnection,
    spanAttributes: options.spanAttributes,
    acquireConnection: flatMap(make(), (scope) => map(provide(transactionAcquirer, scope), (conn) => [scope, conn])),
    begin: (conn) => conn.executeUnprepared(beginTransaction, [], undefined),
    savepoint: (conn, id) => conn.executeUnprepared(savepoint(`effect_sql_${id}`), [], undefined),
    commit: (conn) => conn.executeUnprepared(commit, [], undefined),
    rollback: (conn) => conn.executeUnprepared(rollback, [], undefined),
    rollbackSavepoint: (conn, id) => conn.executeUnprepared(rollbackSavepoint(`effect_sql_${id}`), [], undefined)
  });
  const reactivity = yield* Reactivity;
  const client = Object.assign(make4(getConnection, options.compiler, options.spanAttributes, options.transformRows), {
    [TypeId]: TypeId,
    safe: undefined,
    withTransaction,
    reserve: transactionAcquirer,
    withoutTransforms() {
      if (options.transformRows === undefined) {
        return this;
      }
      const statement2 = make4(getConnection, options.compiler.withoutTransform, options.spanAttributes, undefined);
      const client2 = Object.assign(statement2, {
        ...this,
        ...statement2
      });
      client2.safe = client2;
      client2.withoutTransforms = () => client2;
      return client2;
    },
    reactive: options.reactiveQueue ? (keys, effect2) => options.reactiveQueue(keys, effect2).pipe(map(fromQueue), unwrap) : reactivity.stream,
    reactiveMailbox: options.reactiveQueue ?? reactivity.query
  });
  client.safe = client;
  return client;
});
var makeWithTransaction = (options) => (effect2) => uninterruptibleMask((restore) => useSpan("sql.transaction", {
  kind: "client"
}, (span) => withFiber((fiber) => {
  for (const [key, value] of options.spanAttributes) {
    span.attribute(key, value);
  }
  const services2 = fiber.services;
  const clock = fiber.getRef(Clock);
  const connOption = getOption(services2, options.transactionService);
  const conn = connOption._tag === "Some" ? succeed([undefined, connOption.value[0]]) : options.acquireConnection;
  const id = connOption._tag === "Some" ? connOption.value[1] + 1 : 0;
  return flatMap(conn, ([scope, conn2]) => (id === 0 ? options.begin(conn2) : options.savepoint(conn2, id)).pipe(flatMap(() => provideServices(restore(effect2), add(services2, options.transactionService, [conn2, id]).pipe(add(ParentSpan, span)))), exit, flatMap((exit2) => {
    let effect3;
    if (isSuccess(exit2)) {
      if (id === 0) {
        span.event("db.transaction.commit", clock.currentTimeNanosUnsafe());
        effect3 = orDie(options.commit(conn2));
      } else {
        span.event("db.transaction.savepoint", clock.currentTimeNanosUnsafe());
        effect3 = void_;
      }
    } else {
      span.event("db.transaction.rollback", clock.currentTimeNanosUnsafe());
      effect3 = orDie(id > 0 ? options.rollbackSavepoint(conn2, id) : options.rollback(conn2));
    }
    const withScope = scope !== undefined ? ensuring(effect3, close(scope, exit2)) : effect3;
    return flatMap(withScope, () => exit2);
  })));
})));

class TransactionConnection extends (/* @__PURE__ */ Service()("effect/sql/SqlClient/TransactionConnection")) {
}
var SafeIntegers = /* @__PURE__ */ Reference("effect/sql/SqlClient/SafeIntegers", {
  defaultValue: () => false
});

export { layer, makeCompilerSqlite, defaultTransforms, SqlClient, make5 as make, SafeIntegers };
