@dench.com/cli 3.11.25 → 3.11.26-staging.630
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/crm.ts +320 -33
- package/package.json +1 -1
package/crm.ts
CHANGED
|
@@ -4194,20 +4194,49 @@ async function runSqlCommand(ctx: CrmCliContext): Promise<void> {
|
|
|
4194
4194
|
if (!sql) {
|
|
4195
4195
|
throw new CrmCliError("dench crm sql '<SELECT ... FROM ...>'");
|
|
4196
4196
|
}
|
|
4197
|
-
|
|
4198
|
-
|
|
4199
|
-
|
|
4200
|
-
|
|
4201
|
-
|
|
4202
|
-
|
|
4203
|
-
|
|
4204
|
-
|
|
4205
|
-
|
|
4197
|
+
out(ctx, await callAction(ctx, api.query.queryEntries, sqlQueryArgs(sql)));
|
|
4198
|
+
}
|
|
4199
|
+
|
|
4200
|
+
/** `queryEntries` args for a SQL string. As in `crm query`, Convex rejects
|
|
4201
|
+
* $-prefixed keys, so an operator filter travels as the dslJson string. */
|
|
4202
|
+
export function sqlQueryArgs(sql: string) {
|
|
4203
|
+
const { objectName, dsl } = sqlToQueryDsl(sql);
|
|
4204
|
+
return dsl.filter && containsDollarKey(dsl.filter)
|
|
4205
|
+
? { objectName, dslJson: JSON.stringify(dsl) }
|
|
4206
|
+
: { objectName, dsl };
|
|
4207
|
+
}
|
|
4208
|
+
|
|
4209
|
+
/**
|
|
4210
|
+
* v1: translate the simplest SELECT shape into the query DSL:
|
|
4211
|
+
* "SELECT ... FROM ... WHERE ... ORDER BY ... LIMIT N".
|
|
4212
|
+
*/
|
|
4213
|
+
export function sqlToQueryDsl(sql: string): {
|
|
4214
|
+
objectName: string;
|
|
4215
|
+
dsl: {
|
|
4216
|
+
select?: string[];
|
|
4217
|
+
filter?: Record<string, unknown>;
|
|
4218
|
+
sort?: string;
|
|
4219
|
+
limit: number;
|
|
4220
|
+
};
|
|
4221
|
+
} {
|
|
4222
|
+
const clauses = splitSqlStatement(sql);
|
|
4223
|
+
const {
|
|
4224
|
+
SELECT: selectStr,
|
|
4225
|
+
FROM: tableRaw,
|
|
4226
|
+
WHERE: whereStr,
|
|
4227
|
+
"ORDER BY": sortStr,
|
|
4228
|
+
LIMIT: limitStr,
|
|
4229
|
+
} = clauses ?? {};
|
|
4230
|
+
if (
|
|
4231
|
+
!selectStr ||
|
|
4232
|
+
!tableRaw ||
|
|
4233
|
+
!/^[\w"]+$/.test(tableRaw) ||
|
|
4234
|
+
(limitStr !== undefined && !/^\d+$/.test(limitStr))
|
|
4235
|
+
) {
|
|
4206
4236
|
throw new CrmCliError(
|
|
4207
4237
|
"dench crm sql only supports flat SELECT for now. Use the DSL or duckdb directly.",
|
|
4208
4238
|
);
|
|
4209
4239
|
}
|
|
4210
|
-
const [, selectStr, tableRaw, _whereStr, sortStr, limitStr] = m;
|
|
4211
4240
|
const objectName = tableRaw.replace(/"/g, "");
|
|
4212
4241
|
const select =
|
|
4213
4242
|
selectStr.trim() === "*"
|
|
@@ -4218,23 +4247,237 @@ async function runSqlCommand(ctx: CrmCliContext): Promise<void> {
|
|
|
4218
4247
|
? sortStr
|
|
4219
4248
|
.split(",")
|
|
4220
4249
|
.map((s) => {
|
|
4221
|
-
const
|
|
4222
|
-
|
|
4223
|
-
|
|
4250
|
+
const term = s.trim();
|
|
4251
|
+
const direction = /\s(asc|desc)$/i.exec(term);
|
|
4252
|
+
const field = (direction ? term.slice(0, direction.index) : term)
|
|
4224
4253
|
.trim()
|
|
4225
|
-
.replace(/"/g, "")
|
|
4254
|
+
.replace(/"/g, "");
|
|
4255
|
+
return `${direction?.[1].toLowerCase() === "desc" ? "-" : ""}${field}`;
|
|
4226
4256
|
})
|
|
4227
4257
|
.join(",")
|
|
4228
4258
|
: undefined;
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
|
|
4232
|
-
|
|
4233
|
-
|
|
4234
|
-
|
|
4259
|
+
const filter = whereStr ? sqlWhereToDsl(whereStr) : undefined;
|
|
4260
|
+
return {
|
|
4261
|
+
objectName,
|
|
4262
|
+
dsl: { select, ...(filter ? { filter } : {}), sort, limit },
|
|
4263
|
+
};
|
|
4264
|
+
}
|
|
4265
|
+
|
|
4266
|
+
const SQL_CLAUSES = [
|
|
4267
|
+
["SELECT", /SELECT\s/iy],
|
|
4268
|
+
["FROM", /FROM\s/iy],
|
|
4269
|
+
["WHERE", /WHERE\s/iy],
|
|
4270
|
+
["ORDER BY", /ORDER\s+BY\s/iy],
|
|
4271
|
+
["LIMIT", /LIMIT\s/iy],
|
|
4272
|
+
] as const;
|
|
4273
|
+
|
|
4274
|
+
type SqlClause = (typeof SQL_CLAUSES)[number][0];
|
|
4275
|
+
|
|
4276
|
+
/**
|
|
4277
|
+
* Cuts "SELECT … FROM … [WHERE …] [ORDER BY …] [LIMIT n]" at its keywords,
|
|
4278
|
+
* in that order and outside quotes. A single scan: the one regex it replaced
|
|
4279
|
+
* backtracked cubically on a long run of spaces (14 s for 4,000) and cut a
|
|
4280
|
+
* quoted 'call LIMIT 5' in two.
|
|
4281
|
+
*/
|
|
4282
|
+
function splitSqlStatement(
|
|
4283
|
+
sql: string,
|
|
4284
|
+
): Partial<Record<SqlClause, string>> | null {
|
|
4285
|
+
const text = sql.trim().replace(/;$/, "").trimEnd();
|
|
4286
|
+
if (!/^SELECT\s/i.test(text)) return null;
|
|
4287
|
+
const clauses: Partial<Record<SqlClause, string>> = {};
|
|
4288
|
+
let clause: SqlClause = "SELECT";
|
|
4289
|
+
let start = "SELECT".length;
|
|
4290
|
+
let next = 1;
|
|
4291
|
+
let hasContent = false;
|
|
4292
|
+
let quote: string | null = null;
|
|
4293
|
+
for (let i = start; i < text.length; i++) {
|
|
4294
|
+
const ch = text[i];
|
|
4295
|
+
if (quote) {
|
|
4296
|
+
if (ch === quote) {
|
|
4297
|
+
if (text[i + 1] === quote) i++;
|
|
4298
|
+
else quote = null;
|
|
4299
|
+
}
|
|
4300
|
+
continue;
|
|
4301
|
+
}
|
|
4302
|
+
// A keyword starts a word and follows a clause that has content.
|
|
4303
|
+
if (hasContent && /\s/.test(text[i - 1])) {
|
|
4304
|
+
const hit = SQL_CLAUSES.slice(next).find(([, keyword]) => {
|
|
4305
|
+
keyword.lastIndex = i;
|
|
4306
|
+
return keyword.test(text);
|
|
4307
|
+
});
|
|
4308
|
+
if (hit) {
|
|
4309
|
+
clauses[clause] = text.slice(start, i).trim();
|
|
4310
|
+
clause = hit[0];
|
|
4311
|
+
start = hit[1].lastIndex;
|
|
4312
|
+
next = SQL_CLAUSES.findIndex(([name]) => name === clause) + 1;
|
|
4313
|
+
hasContent = false;
|
|
4314
|
+
i = start - 1;
|
|
4315
|
+
continue;
|
|
4316
|
+
}
|
|
4317
|
+
}
|
|
4318
|
+
if (ch === "'" || ch === '"') quote = ch;
|
|
4319
|
+
if (!/\s/.test(ch)) hasContent = true;
|
|
4320
|
+
}
|
|
4321
|
+
clauses[clause] = text.slice(start).trim();
|
|
4322
|
+
return clauses;
|
|
4323
|
+
}
|
|
4324
|
+
|
|
4325
|
+
const SQL_WHERE_HELP =
|
|
4326
|
+
"dench crm sql supports WHERE with AND-joined comparisons (=, !=, <>, >, >=, <, <=), IN (...), LIKE 'x%' / '%x' / '%x%' and IS [NOT] NULL. For anything else use dench crm query --where '{\"Field\":{\"$op\":value}}'.";
|
|
4327
|
+
|
|
4328
|
+
/**
|
|
4329
|
+
* Translate a WHERE clause into the query DSL. A clause it cannot translate
|
|
4330
|
+
* is an error, never ignored: an ignored WHERE returned every row while
|
|
4331
|
+
* ORDER BY and LIMIT still applied, so the result looked filtered.
|
|
4332
|
+
*/
|
|
4333
|
+
function sqlWhereToDsl(whereStr: string): Record<string, unknown> {
|
|
4334
|
+
const where: Record<string, Record<string, unknown>> = {};
|
|
4335
|
+
const add = (field: string, op: string, value: unknown) => {
|
|
4336
|
+
where[field] = { ...where[field], [op]: value };
|
|
4337
|
+
};
|
|
4338
|
+
for (const clause of splitSqlAnd(whereStr)) {
|
|
4339
|
+
// The operand is sliced off, not captured: `\s*(.+)$` backtracks on long
|
|
4340
|
+
// whitespace runs.
|
|
4341
|
+
const m =
|
|
4342
|
+
/^("(?:[^"]|"")+"|[A-Za-z_]\w*)\s*(=|!=|<>|>=|<=|>|<|NOT\s+IN|IN|NOT\s+LIKE|LIKE|IS\s+NOT|IS)/i.exec(
|
|
4343
|
+
clause,
|
|
4344
|
+
);
|
|
4345
|
+
const raw = m ? clause.slice(m[0].length).trim() : "";
|
|
4346
|
+
if (!m || !raw) throw new CrmCliError(SQL_WHERE_HELP);
|
|
4347
|
+
const field = m[1].startsWith('"')
|
|
4348
|
+
? m[1].slice(1, -1).replace(/""/g, '"')
|
|
4349
|
+
: m[1];
|
|
4350
|
+
const op = m[2].toUpperCase().replace(/\s+/g, " ");
|
|
4351
|
+
if (op === "IS" || op === "IS NOT") {
|
|
4352
|
+
if (!/^NULL$/i.test(raw)) throw new CrmCliError(SQL_WHERE_HELP);
|
|
4353
|
+
add(field, "$exists", op === "IS NOT");
|
|
4354
|
+
continue;
|
|
4355
|
+
}
|
|
4356
|
+
if (op === "IN" || op === "NOT IN") {
|
|
4357
|
+
const list = /^\(([\s\S]*)\)$/.exec(raw);
|
|
4358
|
+
if (!list) throw new CrmCliError(SQL_WHERE_HELP);
|
|
4359
|
+
const values = splitSqlList(list[1]).map(sqlLiteral);
|
|
4360
|
+
add(field, op === "IN" ? "$in" : "$nin", values);
|
|
4361
|
+
continue;
|
|
4362
|
+
}
|
|
4363
|
+
const value = sqlLiteral(raw);
|
|
4364
|
+
if (op === "LIKE") {
|
|
4365
|
+
if (typeof value !== "string") throw new CrmCliError(SQL_WHERE_HELP);
|
|
4366
|
+
const inner = value.replace(/^%/, "").replace(/%$/, "");
|
|
4367
|
+
if (!inner || /[%_]/.test(inner)) throw new CrmCliError(SQL_WHERE_HELP);
|
|
4368
|
+
const starts = value.endsWith("%") && !value.startsWith("%");
|
|
4369
|
+
const ends = value.startsWith("%") && !value.endsWith("%");
|
|
4370
|
+
const contains = value.startsWith("%") && value.endsWith("%");
|
|
4371
|
+
if (starts) add(field, "$startsWith", inner);
|
|
4372
|
+
else if (ends) add(field, "$endsWith", inner);
|
|
4373
|
+
else if (contains) add(field, "$contains", inner);
|
|
4374
|
+
else add(field, "$eq", inner);
|
|
4375
|
+
continue;
|
|
4376
|
+
}
|
|
4377
|
+
if (op === "NOT LIKE") throw new CrmCliError(SQL_WHERE_HELP);
|
|
4378
|
+
if ([">", ">=", "<", "<="].includes(op)) {
|
|
4379
|
+
if (typeof value !== "number") throw new CrmCliError(SQL_WHERE_HELP);
|
|
4380
|
+
const dslOp = { ">": "$gt", ">=": "$gte", "<": "$lt", "<=": "$lte" }[op];
|
|
4381
|
+
add(field, dslOp as string, value);
|
|
4382
|
+
continue;
|
|
4383
|
+
}
|
|
4384
|
+
add(field, op === "=" ? "$eq" : "$ne", value);
|
|
4385
|
+
}
|
|
4386
|
+
// `{ Field: value }` is the DSL's plain equality; keep that shape.
|
|
4387
|
+
return Object.fromEntries(
|
|
4388
|
+
Object.entries(where).map(([field, ops]) =>
|
|
4389
|
+
Object.keys(ops).length === 1 && "$eq" in ops
|
|
4390
|
+
? [field, ops.$eq]
|
|
4391
|
+
: [field, ops],
|
|
4392
|
+
),
|
|
4235
4393
|
);
|
|
4236
4394
|
}
|
|
4237
4395
|
|
|
4396
|
+
/** `word`, any case, at `at` and followed by whitespace. */
|
|
4397
|
+
function isSqlWordAt(text: string, at: number, word: string): boolean {
|
|
4398
|
+
return (
|
|
4399
|
+
text.slice(at, at + word.length).toUpperCase() === word &&
|
|
4400
|
+
/\s/.test(text[at + word.length] ?? "")
|
|
4401
|
+
);
|
|
4402
|
+
}
|
|
4403
|
+
|
|
4404
|
+
/** Splits on top-level AND, outside quotes; OR and parentheses are refused. */
|
|
4405
|
+
function splitSqlAnd(whereStr: string): string[] {
|
|
4406
|
+
const clauses: string[] = [];
|
|
4407
|
+
let buf = "";
|
|
4408
|
+
let quote: string | null = null;
|
|
4409
|
+
for (let i = 0; i < whereStr.length; i++) {
|
|
4410
|
+
const ch = whereStr[i];
|
|
4411
|
+
if (quote) {
|
|
4412
|
+
buf += ch;
|
|
4413
|
+
if (ch === quote) {
|
|
4414
|
+
if (whereStr[i + 1] === quote) buf += whereStr[++i];
|
|
4415
|
+
else quote = null;
|
|
4416
|
+
}
|
|
4417
|
+
continue;
|
|
4418
|
+
}
|
|
4419
|
+
if (ch === "'" || ch === '"') {
|
|
4420
|
+
quote = ch;
|
|
4421
|
+
buf += ch;
|
|
4422
|
+
continue;
|
|
4423
|
+
}
|
|
4424
|
+
if (ch === "(" && !/\bIN$/i.test(buf.trimEnd())) {
|
|
4425
|
+
throw new CrmCliError(SQL_WHERE_HELP);
|
|
4426
|
+
}
|
|
4427
|
+
// Only where a whitespace run starts, so each run is read once.
|
|
4428
|
+
if (/\s/.test(ch) && !/\s/.test(whereStr[i - 1] ?? "")) {
|
|
4429
|
+
let word = i;
|
|
4430
|
+
while (/\s/.test(whereStr[word] ?? "")) word++;
|
|
4431
|
+
if (isSqlWordAt(whereStr, word, "OR")) {
|
|
4432
|
+
throw new CrmCliError(SQL_WHERE_HELP);
|
|
4433
|
+
}
|
|
4434
|
+
if (isSqlWordAt(whereStr, word, "AND")) {
|
|
4435
|
+
clauses.push(buf);
|
|
4436
|
+
buf = "";
|
|
4437
|
+
i = word + "AND".length - 1;
|
|
4438
|
+
continue;
|
|
4439
|
+
}
|
|
4440
|
+
}
|
|
4441
|
+
buf += ch;
|
|
4442
|
+
}
|
|
4443
|
+
clauses.push(buf);
|
|
4444
|
+
return clauses.map((clause) => clause.trim()).filter(Boolean);
|
|
4445
|
+
}
|
|
4446
|
+
|
|
4447
|
+
function splitSqlList(list: string): string[] {
|
|
4448
|
+
const items: string[] = [];
|
|
4449
|
+
let buf = "";
|
|
4450
|
+
let inString = false;
|
|
4451
|
+
for (let i = 0; i < list.length; i++) {
|
|
4452
|
+
const ch = list[i];
|
|
4453
|
+
if (ch === "'") {
|
|
4454
|
+
if (inString && list[i + 1] === "'") {
|
|
4455
|
+
buf += "''";
|
|
4456
|
+
i++;
|
|
4457
|
+
continue;
|
|
4458
|
+
}
|
|
4459
|
+
inString = !inString;
|
|
4460
|
+
}
|
|
4461
|
+
if (ch === "," && !inString) {
|
|
4462
|
+
items.push(buf.trim());
|
|
4463
|
+
buf = "";
|
|
4464
|
+
continue;
|
|
4465
|
+
}
|
|
4466
|
+
buf += ch;
|
|
4467
|
+
}
|
|
4468
|
+
if (buf.trim()) items.push(buf.trim());
|
|
4469
|
+
return items;
|
|
4470
|
+
}
|
|
4471
|
+
|
|
4472
|
+
function sqlLiteral(raw: string): string | number | boolean {
|
|
4473
|
+
const text = raw.trim();
|
|
4474
|
+
const quoted = /^'((?:[^']|'')*)'$/.exec(text);
|
|
4475
|
+
if (quoted) return quoted[1].replace(/''/g, "'");
|
|
4476
|
+
if (/^-?\d+(\.\d+)?$/.test(text)) return Number(text);
|
|
4477
|
+
if (/^(true|false)$/i.test(text)) return text.toLowerCase() === "true";
|
|
4478
|
+
throw new CrmCliError(SQL_WHERE_HELP);
|
|
4479
|
+
}
|
|
4480
|
+
|
|
4238
4481
|
// ── CRM enrichment gateway orchestration ─────────────────────────────────
|
|
4239
4482
|
|
|
4240
4483
|
type CrmFieldForEnrichment = FieldCandidate & {
|
|
@@ -4770,14 +5013,15 @@ async function runPeopleCommand(ctx: CrmCliContext): Promise<void> {
|
|
|
4770
5013
|
"dench crm people upsert: --data must include at least one field.",
|
|
4771
5014
|
);
|
|
4772
5015
|
}
|
|
4773
|
-
|
|
4774
|
-
|
|
4775
|
-
await callMutation(ctx, api.entries.create, {
|
|
4776
|
-
objectName: "people",
|
|
4777
|
-
data,
|
|
4778
|
-
...runContextArgs(ctx),
|
|
4779
|
-
}),
|
|
5016
|
+
const matchField = ["Email", "Email Address", "LinkedIn URL"].find(
|
|
5017
|
+
(field) => typeof data[field] === "string" && data[field].trim(),
|
|
4780
5018
|
);
|
|
5019
|
+
if (!matchField) {
|
|
5020
|
+
throw new CrmCliError(
|
|
5021
|
+
'dench crm people upsert matches on "Email" / "Email Address" (or "LinkedIn URL"); include one in --data. To add a person without either, use `dench crm entries create people --data \'{...}\'`.',
|
|
5022
|
+
);
|
|
5023
|
+
}
|
|
5024
|
+
await upsertEntryByField(ctx, "people", data, matchField);
|
|
4781
5025
|
return;
|
|
4782
5026
|
}
|
|
4783
5027
|
case "enrich": {
|
|
@@ -4804,6 +5048,51 @@ async function runPeopleCommand(ctx: CrmCliContext): Promise<void> {
|
|
|
4804
5048
|
}
|
|
4805
5049
|
}
|
|
4806
5050
|
|
|
5051
|
+
/**
|
|
5052
|
+
* The upsert shortcuts: update the row whose `matchField` already holds this
|
|
5053
|
+
* value, or create it. They used to call `entries.create` with no lookup, so
|
|
5054
|
+
* every call added a duplicate person or company. Same machinery and seed
|
|
5055
|
+
* key as `entries create-many --dedupe-key <field> --on-conflict update`.
|
|
5056
|
+
*/
|
|
5057
|
+
async function upsertEntryByField(
|
|
5058
|
+
ctx: CrmCliContext,
|
|
5059
|
+
objectName: string,
|
|
5060
|
+
data: JsonRecord,
|
|
5061
|
+
matchField: string,
|
|
5062
|
+
): Promise<void> {
|
|
5063
|
+
const command = `crm ${objectName === "people" ? "people" : "companies"} upsert`;
|
|
5064
|
+
const seedKey = dedupeKeyFromColumn({
|
|
5065
|
+
prefix: `many:${objectName}:${matchField}`,
|
|
5066
|
+
column: matchField,
|
|
5067
|
+
row: data,
|
|
5068
|
+
rowIndex: 0,
|
|
5069
|
+
command,
|
|
5070
|
+
});
|
|
5071
|
+
const { results, references } = await applyBatchOpsInChunks(
|
|
5072
|
+
ctx,
|
|
5073
|
+
[
|
|
5074
|
+
{
|
|
5075
|
+
type: "entries.create",
|
|
5076
|
+
objectName,
|
|
5077
|
+
data,
|
|
5078
|
+
seedKey,
|
|
5079
|
+
matchField,
|
|
5080
|
+
rowIndex: 1,
|
|
5081
|
+
},
|
|
5082
|
+
],
|
|
5083
|
+
undefined,
|
|
5084
|
+
false,
|
|
5085
|
+
"update",
|
|
5086
|
+
true,
|
|
5087
|
+
);
|
|
5088
|
+
const [result] = results;
|
|
5089
|
+
const linked = withCrmEntryDeepLinks(ctx, objectName, result);
|
|
5090
|
+
outWithReferences(ctx, {
|
|
5091
|
+
...boundWorkspaceReferences(references, results.length),
|
|
5092
|
+
...(isJsonRecord(linked) ? linked : { result: result ?? null }),
|
|
5093
|
+
});
|
|
5094
|
+
}
|
|
5095
|
+
|
|
4807
5096
|
async function runCompaniesCommand(ctx: CrmCliContext): Promise<void> {
|
|
4808
5097
|
const verb = ctx.args.shift();
|
|
4809
5098
|
switch (verb) {
|
|
@@ -4833,13 +5122,11 @@ async function runCompaniesCommand(ctx: CrmCliContext): Promise<void> {
|
|
|
4833
5122
|
"dench crm companies upsert requires at least --domain or --name. For arbitrary fields, use `dench crm entries create company --data '{...}'`.",
|
|
4834
5123
|
);
|
|
4835
5124
|
}
|
|
4836
|
-
|
|
5125
|
+
await upsertEntryByField(
|
|
4837
5126
|
ctx,
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
...runContextArgs(ctx),
|
|
4842
|
-
}),
|
|
5127
|
+
"company",
|
|
5128
|
+
data,
|
|
5129
|
+
domain ? "Domain" : "Name",
|
|
4843
5130
|
);
|
|
4844
5131
|
return;
|
|
4845
5132
|
}
|