@nocobase/database 2.1.0-beta.2 → 2.1.0-beta.21

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/README.md CHANGED
@@ -1,17 +1,24 @@
1
1
  # NocoBase
2
2
 
3
3
  <video width="100%" controls>
4
- <source src="https://static-docs.nocobase.com/NocoBase0510.mp4" type="video/mp4">
4
+ <source src="https://github.com/user-attachments/assets/4d11a87b-00e2-48f3-9bf7-389d21072d13" type="video/mp4">
5
5
  </video>
6
6
 
7
+ <p align="center">
8
+ <a href="https://trendshift.io/repositories/4112" target="_blank"><img src="https://trendshift.io/api/badge/repositories/4112" alt="nocobase%2Fnocobase | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
9
+ <a href="https://www.producthunt.com/posts/nocobase?embed=true&utm_source=badge-top-post-topic-badge&utm_medium=badge&utm_souce=badge-nocobase" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/top-post-topic-badge.svg?post_id=456520&theme=light&period=weekly&topic_id=267" alt="NocoBase - Scalability&#0045;first&#0044;&#0032;open&#0045;source&#0032;no&#0045;code&#0032;platform | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
10
+ </p>
7
11
 
8
12
  ## What is NocoBase
9
13
 
10
- NocoBase is a scalability-first, open-source no-code development platform.
11
- Instead of investing years of time and millions of dollars in research and development, deploy NocoBase in a few minutes and you'll have a private, controllable, and extremely scalable no-code development platform!
14
+ NocoBase is the most extensible AI-powered no-code platform.
15
+ Total control. Infinite extensibility. AI collaboration.
16
+ Enable your team to adapt quickly and cut costs dramatically.
17
+ No years of development. No millions wasted.
18
+ Deploy NocoBase in minutes — and take control of everything.
12
19
 
13
20
  Homepage:
14
- https://www.nocobase.com/
21
+ https://www.nocobase.com/
15
22
 
16
23
  Online Demo:
17
24
  https://demo.nocobase.com/new
@@ -19,12 +26,74 @@ https://demo.nocobase.com/new
19
26
  Documents:
20
27
  https://docs.nocobase.com/
21
28
 
22
- Commericial license & plugins:
23
- https://www.nocobase.com/en/commercial
29
+ Forum:
30
+ https://forum.nocobase.com/
24
31
 
25
- License agreement:
26
- https://www.nocobase.com/en/agreement
32
+ Use Cases:
33
+ https://www.nocobase.com/en/blog/tags/customer-stories
27
34
 
35
+ ## Release Notes
28
36
 
29
- ## Contact Us:
30
- hello@nocobase.com
37
+ Our [blog](https://www.nocobase.com/en/blog/timeline) is regularly updated with release notes and provides a weekly summary.
38
+
39
+ ## Distinctive features
40
+
41
+ ### 1. Data model-driven, not form/table–driven
42
+
43
+ Instead of being constrained by forms or tables, NocoBase adopts a data model–driven approach, separating data structure from user interface to unlock unlimited possibilities.
44
+
45
+ - UI and data structure are fully decoupled
46
+ - Multiple blocks and actions can be created for the same table or record in any quantity or form
47
+ - Supports the main database, external databases, and third-party APIs as data sources
48
+
49
+ ![model](https://static-docs.nocobase.com/model.png)
50
+
51
+ ### 2. AI employees, integrated into your business systems
52
+ Unlike standalone AI demos, NocoBase allows you to embed AI capabilities seamlessly into your interfaces, workflows, and data context, making AI truly useful in real business scenarios.
53
+
54
+ - Define AI employees for roles such as translator, analyst, researcher, or assistant
55
+ - Seamless AI–human collaboration in interfaces and workflows
56
+ - Ensure AI usage is secure, transparent, and customizable for your business needs
57
+
58
+ ![AI-employee](https://static-docs.nocobase.com/ai-employee-home.png)
59
+
60
+ ### 3. What you see is what you get, incredibly easy to use
61
+
62
+ While enabling the development of complex business systems, NocoBase keeps the experience simple and intuitive.
63
+
64
+ - One-click switch between usage mode and configuration mode
65
+ - Pages serve as a canvas to arrange blocks and actions, similar to Notion
66
+ - Configuration mode is designed for ordinary users, not just programmers
67
+
68
+ ![wysiwyg](https://static-docs.nocobase.com/wysiwyg.gif)
69
+
70
+ ### 4. Everything is a plugin, designed for extension
71
+ Adding more no-code features will never cover every business case. NocoBase is built for extension through its plugin-based microkernel architecture.
72
+
73
+ - All functionalities are plugins, similar to WordPress
74
+ - Plugins are ready to use upon installation
75
+ - Pages, blocks, actions, APIs, and data sources can all be extended through custom plugins
76
+
77
+ ![plugins](https://static-docs.nocobase.com/plugins.png)
78
+
79
+ ## Installation
80
+
81
+ NocoBase supports three installation methods:
82
+
83
+ - <a target="_blank" href="https://docs.nocobase.com/welcome/getting-started/installation/docker-compose">Installing With Docker (👍Recommended)</a>
84
+
85
+ Suitable for no-code scenarios, no code to write. When upgrading, just download the latest image and reboot.
86
+
87
+ - <a target="_blank" href="https://docs.nocobase.com/welcome/getting-started/installation/create-nocobase-app">Installing from create-nocobase-app CLI</a>
88
+
89
+ The business code of the project is completely independent and supports low-code development.
90
+
91
+ - <a target="_blank" href="https://docs.nocobase.com/welcome/getting-started/installation/git-clone">Installing from Git source code</a>
92
+
93
+ If you want to experience the latest unreleased version, or want to participate in the contribution, you need to make changes and debug on the source code, it is recommended to choose this installation method, which requires a high level of development skills, and if the code has been updated, you can git pull the latest code.
94
+
95
+ ## How NocoBase works
96
+
97
+ <video width="100%" controls>
98
+ <source src="https://github.com/user-attachments/assets/8d183b44-9bb5-4792-b08f-bc08fe8dfaaf" type="video/mp4">
99
+ </video>
package/lib/database.d.ts CHANGED
@@ -45,6 +45,7 @@ export interface IDatabaseOptions extends Options {
45
45
  migrator?: any;
46
46
  usingBigIntForId?: boolean;
47
47
  underscored?: boolean;
48
+ rawTimezone?: string;
48
49
  logger?: LoggerOptions | Logger;
49
50
  customHooks?: any;
50
51
  instanceId?: string;
@@ -75,16 +75,20 @@ const queryParentSQL = /* @__PURE__ */ __name((options) => {
75
75
  const targetKeyField = collection.model.rawAttributes[targetKey].field;
76
76
  const queryInterface = db.sequelize.getQueryInterface();
77
77
  const q = queryInterface.quoteIdentifier.bind(queryInterface);
78
- return `WITH RECURSIVE cte AS (
78
+ const placeholders = nodeIds.map((_, index) => `$${index + 1}`).join(", ");
79
+ return {
80
+ sql: `WITH RECURSIVE cte AS (
79
81
  SELECT ${q(targetKeyField)}, ${q(foreignKeyField)}
80
82
  FROM ${tableName}
81
- WHERE ${q(targetKeyField)} IN ('${nodeIds.join("','")}')
83
+ WHERE ${q(targetKeyField)} IN (${placeholders})
82
84
  UNION ALL
83
85
  SELECT t.${q(targetKeyField)}, t.${q(foreignKeyField)}
84
86
  FROM ${tableName} AS t
85
87
  INNER JOIN cte ON t.${q(targetKeyField)} = cte.${q(foreignKeyField)}
86
88
  )
87
- SELECT ${q(targetKeyField)} AS ${q(targetKey)}, ${q(foreignKeyField)} AS ${q(foreignKey)} FROM cte`;
89
+ SELECT ${q(targetKeyField)} AS ${q(targetKey)}, ${q(foreignKeyField)} AS ${q(foreignKey)} FROM cte`,
90
+ bind: nodeIds
91
+ };
88
92
  }, "queryParentSQL");
89
93
  const _EagerLoadingTree = class _EagerLoadingTree {
90
94
  root;
@@ -149,6 +153,11 @@ const _EagerLoadingTree = class _EagerLoadingTree {
149
153
  const { sourceKey } = association;
150
154
  pushAttribute(eagerLoadingTreeParent, sourceKey);
151
155
  }
156
+ if (associationType == "BelongsToArray") {
157
+ const { foreignKey, targetKey } = association;
158
+ pushAttribute(eagerLoadingTreeParent, foreignKey);
159
+ pushAttribute(child, targetKey);
160
+ }
152
161
  eagerLoadingTreeParent.children.push(child);
153
162
  if (include.include) {
154
163
  traverseIncludeOption(include.include, child);
@@ -300,7 +309,7 @@ const _EagerLoadingTree = class _EagerLoadingTree {
300
309
  });
301
310
  if (node.includeOption.recursively && instances.length > 0) {
302
311
  const targetKey = association.targetKey;
303
- const sql = queryParentSQL({
312
+ const { sql, bind } = queryParentSQL({
304
313
  db: this.db,
305
314
  collection: collection2,
306
315
  foreignKey,
@@ -308,6 +317,7 @@ const _EagerLoadingTree = class _EagerLoadingTree {
308
317
  nodeIds: instances.map((instance) => instance.get(targetKey))
309
318
  });
310
319
  const results = await this.db.sequelize.query(sql, {
320
+ bind,
311
321
  type: "SELECT",
312
322
  transaction
313
323
  });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ export declare class AssociationNotFoundError extends Error {
10
+ constructor(message: string);
11
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var association_not_found_error_exports = {};
29
+ __export(association_not_found_error_exports, {
30
+ AssociationNotFoundError: () => AssociationNotFoundError
31
+ });
32
+ module.exports = __toCommonJS(association_not_found_error_exports);
33
+ const _AssociationNotFoundError = class _AssociationNotFoundError extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = "AssociationNotFoundError";
37
+ }
38
+ };
39
+ __name(_AssociationNotFoundError, "AssociationNotFoundError");
40
+ let AssociationNotFoundError = _AssociationNotFoundError;
41
+ // Annotate the CommonJS export names for ESM import in node:
42
+ 0 && (module.exports = {
43
+ AssociationNotFoundError
44
+ });
@@ -43,7 +43,7 @@ const _RelationField = class _RelationField extends import_field.Field {
43
43
  return this.options.foreignKey;
44
44
  }
45
45
  get sourceKey() {
46
- return this.options.sourceKey || this.collection.model.primaryKeyAttribute;
46
+ return this.options.sourceKey || this.collection.filterTargetKey;
47
47
  }
48
48
  get targetKey() {
49
49
  return this.options.targetKey || this.TargetModel.primaryKeyAttribute;
package/lib/index.d.ts CHANGED
@@ -32,6 +32,9 @@ export * from './relation-repository/hasmany-repository';
32
32
  export * from './relation-repository/hasone-repository';
33
33
  export * from './relation-repository/multiple-relation-repository';
34
34
  export * from './relation-repository/single-relation-repository';
35
+ export * from './query/builder';
36
+ export * from './query/formatter';
37
+ export * from './query/types';
35
38
  export * from './repository';
36
39
  export * from './relation-repository/relation-repository';
37
40
  export { default as sqlParser, SQLParserTypes } from './sql-parser';
package/lib/index.js CHANGED
@@ -93,6 +93,9 @@ __reExport(src_exports, require("./relation-repository/hasmany-repository"), mod
93
93
  __reExport(src_exports, require("./relation-repository/hasone-repository"), module.exports);
94
94
  __reExport(src_exports, require("./relation-repository/multiple-relation-repository"), module.exports);
95
95
  __reExport(src_exports, require("./relation-repository/single-relation-repository"), module.exports);
96
+ __reExport(src_exports, require("./query/builder"), module.exports);
97
+ __reExport(src_exports, require("./query/formatter"), module.exports);
98
+ __reExport(src_exports, require("./query/types"), module.exports);
96
99
  __reExport(src_exports, require("./repository"), module.exports);
97
100
  __reExport(src_exports, require("./relation-repository/relation-repository"), module.exports);
98
101
  var import_sql_parser = __toESM(require("./sql-parser"));
@@ -157,6 +160,9 @@ var import_filter_include = require("./utils/filter-include");
157
160
  ...require("./relation-repository/hasone-repository"),
158
161
  ...require("./relation-repository/multiple-relation-repository"),
159
162
  ...require("./relation-repository/single-relation-repository"),
163
+ ...require("./query/builder"),
164
+ ...require("./query/formatter"),
165
+ ...require("./query/types"),
160
166
  ...require("./repository"),
161
167
  ...require("./relation-repository/relation-repository"),
162
168
  ...require("./update-associations"),
@@ -42,7 +42,7 @@ const _ToOneInterface = class _ToOneInterface extends import_base_interface.Base
42
42
  const { filterKey, associationField, targetCollection, transaction } = ctx;
43
43
  const targetInstance = await targetCollection.repository.findOne({
44
44
  filter: {
45
- [filterKey]: str
45
+ [filterKey]: str.toString()
46
46
  },
47
47
  transaction
48
48
  });
@@ -22,6 +22,7 @@ export declare class OptionsParser {
22
22
  model: ModelStatic<any>;
23
23
  filterParser: FilterParser;
24
24
  context: OptionsParserContext;
25
+ associationNotFoundWarnings: string[];
25
26
  constructor(options: FindOptions, context: OptionsParserContext);
26
27
  static appendInheritInspectAttribute(include: any, collection: any): any;
27
28
  isAssociation(key: string): boolean;
@@ -44,6 +44,7 @@ var import_lodash = __toESM(require("lodash"));
44
44
  var import_sequelize = require("sequelize");
45
45
  var import_filter_parser = __toESM(require("./filter-parser"));
46
46
  var import_qs = __toESM(require("qs"));
47
+ var import_association_not_found_error = require("./errors/association-not-found-error");
47
48
  const debug = require("debug")("noco-database");
48
49
  const _OptionsParser = class _OptionsParser {
49
50
  options;
@@ -52,6 +53,7 @@ const _OptionsParser = class _OptionsParser {
52
53
  model;
53
54
  filterParser;
54
55
  context;
56
+ associationNotFoundWarnings = [];
55
57
  constructor(options, context) {
56
58
  const { collection } = context;
57
59
  this.collection = collection;
@@ -301,7 +303,7 @@ const _OptionsParser = class _OptionsParser {
301
303
  }
302
304
  const sortedAppends = import_lodash.default.sortBy(appendList, (append) => append.split(".").length);
303
305
  const setInclude = /* @__PURE__ */ __name((model, queryParams, append, parentAs) => {
304
- var _a;
306
+ var _a, _b;
305
307
  const appendWithOptions = this.parseAppendWithOptions(append);
306
308
  append = appendWithOptions.name;
307
309
  const appendFields = append.split(".");
@@ -314,7 +316,7 @@ const _OptionsParser = class _OptionsParser {
314
316
  if (appendFields.length == 2) {
315
317
  const association = associations[appendFields[0]];
316
318
  if (!association) {
317
- throw new Error(`association ${appendFields[0]} in ${model.name} not found`);
319
+ throw new import_association_not_found_error.AssociationNotFoundError(`association ${appendFields[0]} in ${model.name} not found`);
318
320
  }
319
321
  const associationModel = associations[appendFields[0]].target;
320
322
  if (associationModel.rawAttributes[appendFields[1]]) {
@@ -341,7 +343,13 @@ const _OptionsParser = class _OptionsParser {
341
343
  if (existIncludeIndex == -1) {
342
344
  const association = associations[appendAssociation];
343
345
  if (!association) {
344
- throw new Error(`association ${appendAssociation} in ${model.name} not found`);
346
+ throw new import_association_not_found_error.AssociationNotFoundError(`association ${appendAssociation} in ${model.name} not found`);
347
+ }
348
+ const targetCollectionName = (_b = this.database.getCollectionByModelName(association.target.name)) == null ? void 0 : _b.name;
349
+ if (!targetCollectionName) {
350
+ throw new import_association_not_found_error.AssociationNotFoundError(
351
+ `target collection for association ${appendAssociation} in ${model.name} not found`
352
+ );
345
353
  }
346
354
  let includeOptions = {
347
355
  association: appendAssociation,
@@ -394,7 +402,15 @@ const _OptionsParser = class _OptionsParser {
394
402
  }
395
403
  }, "setInclude");
396
404
  for (const append of sortedAppends) {
397
- setInclude(this.model, filterParams, append);
405
+ try {
406
+ setInclude(this.model, filterParams, append);
407
+ } catch (error) {
408
+ if (error instanceof import_association_not_found_error.AssociationNotFoundError) {
409
+ this.associationNotFoundWarnings.push(error.message);
410
+ continue;
411
+ }
412
+ throw error;
413
+ }
398
414
  }
399
415
  debug("filter params: %o", filterParams);
400
416
  return filterParams;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ import { FindOptions as SequelizeFindOptions } from 'sequelize';
10
+ import { Collection } from '../collection';
11
+ import { Database } from '../database';
12
+ import { QueryOptions } from './types';
13
+ export declare function buildQuery(database: Database, collection: Collection, options?: QueryOptions): {
14
+ queryOptions: SequelizeFindOptions<any>;
15
+ fieldMap: Record<string, any>;
16
+ };
17
+ export declare function normalizeQueryResult(data: any[], fieldMap: Record<string, any>): any[];
@@ -0,0 +1,268 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
17
+ var __export = (target, all) => {
18
+ for (var name in all)
19
+ __defProp(target, name, { get: all[name], enumerable: true });
20
+ };
21
+ var __copyProps = (to, from, except, desc) => {
22
+ if (from && typeof from === "object" || typeof from === "function") {
23
+ for (let key of __getOwnPropNames(from))
24
+ if (!__hasOwnProp.call(to, key) && key !== except)
25
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
26
+ }
27
+ return to;
28
+ };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
30
+ // If the importer is in node compatibility mode or this is not an ESM
31
+ // file that has been converted to a CommonJS file using a Babel-
32
+ // compatible transform (i.e. "__esModule" has not been set), then set
33
+ // "default" to the CommonJS "module.exports" for node compatibility.
34
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
+ mod
36
+ ));
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+ var builder_exports = {};
39
+ __export(builder_exports, {
40
+ buildQuery: () => buildQuery,
41
+ normalizeQueryResult: () => normalizeQueryResult
42
+ });
43
+ module.exports = __toCommonJS(builder_exports);
44
+ var import_filter_parser = __toESM(require("../filter-parser"));
45
+ var import_formatter = require("./formatter");
46
+ var import_mysql = require("./formatters/mysql");
47
+ var import_oracle = require("./formatters/oracle");
48
+ var import_postgres = require("./formatters/postgres");
49
+ var import_sqlite = require("./formatters/sqlite");
50
+ var import_having = require("./having");
51
+ const ALLOWED_AGG_FUNCS = ["sum", "count", "avg", "min", "max"];
52
+ const ALLOWED_ORDER_DIRECTIONS = ["ASC", "DESC"];
53
+ function createQueryFormatter(database) {
54
+ switch (database.sequelize.getDialect()) {
55
+ case "sqlite":
56
+ return new import_sqlite.SQLiteQueryFormatter(database.sequelize, database.options.rawTimezone);
57
+ case "postgres":
58
+ return new import_postgres.PostgresQueryFormatter(database.sequelize, database.options.rawTimezone);
59
+ case "mysql":
60
+ case "mariadb":
61
+ return new import_mysql.MySQLQueryFormatter(database.sequelize, database.options.rawTimezone);
62
+ case "oracle":
63
+ return new import_oracle.OracleQueryFormatter(database.sequelize, database.options.rawTimezone);
64
+ default:
65
+ return new class extends import_formatter.QueryFormatter {
66
+ formatDate(field, _format, _timezone, _preserveLocalTime) {
67
+ return field;
68
+ }
69
+ formatUnixTimestamp(field, _format, _accuracy, _timezone) {
70
+ return this.sequelize.col(field);
71
+ }
72
+ }(database.sequelize, database.options.rawTimezone);
73
+ }
74
+ }
75
+ __name(createQueryFormatter, "createQueryFormatter");
76
+ function parseSelectedField(database, collection, selected) {
77
+ var _a, _b, _c, _d, _e;
78
+ const collectionName = collection.name;
79
+ const fields = collection.fields;
80
+ let target;
81
+ let name;
82
+ const fieldPath = Array.isArray(selected.field) ? selected.field : selected.field.split(".").filter(Boolean);
83
+ if (fieldPath.length === 1) {
84
+ name = fieldPath[0];
85
+ } else {
86
+ [target, name] = fieldPath;
87
+ }
88
+ const rawAttributes = collection.model.getAttributes();
89
+ let field = ((_a = rawAttributes[name]) == null ? void 0 : _a.field) || name;
90
+ let fieldType = (_b = fields.get(name)) == null ? void 0 : _b.type;
91
+ let fieldOptions = (_c = fields.get(name)) == null ? void 0 : _c.options;
92
+ if (target) {
93
+ const targetField = fields.get(target);
94
+ const targetCollection = database.getCollection(targetField.target);
95
+ const targetFields = targetCollection.fields;
96
+ fieldType = (_d = targetFields.get(name)) == null ? void 0 : _d.type;
97
+ fieldOptions = (_e = targetFields.get(name)) == null ? void 0 : _e.options;
98
+ field = `${target}.${field}`;
99
+ name = `${target}.${name}`;
100
+ } else {
101
+ field = `${collectionName}.${field}`;
102
+ }
103
+ return {
104
+ ...selected,
105
+ field,
106
+ name,
107
+ type: fieldType,
108
+ options: fieldOptions,
109
+ alias: selected.alias || name,
110
+ target
111
+ };
112
+ }
113
+ __name(parseSelectedField, "parseSelectedField");
114
+ function buildQuery(database, collection, options = {}) {
115
+ var _a;
116
+ const sequelize = database.sequelize;
117
+ const formatter = createQueryFormatter(database);
118
+ const measures = (options.measures || []).map((measure) => parseSelectedField(database, collection, measure));
119
+ const dimensions = (options.dimensions || []).map((dimension) => parseSelectedField(database, collection, dimension));
120
+ const orders = (options.orders || []).map((order2) => parseSelectedField(database, collection, order2));
121
+ const models = {};
122
+ [...measures, ...dimensions, ...orders].forEach((item) => {
123
+ var _a2;
124
+ if (item.target && !models[item.target]) {
125
+ models[item.target] = { type: (_a2 = collection.fields.get(item.target)) == null ? void 0 : _a2.type };
126
+ }
127
+ });
128
+ const include = Object.entries(models).map(([target, { type }]) => {
129
+ let includeOptions = {
130
+ association: target,
131
+ attributes: []
132
+ };
133
+ if (type === "belongsToMany") {
134
+ includeOptions.through = { attributes: [] };
135
+ }
136
+ if (type === "belongsToArray") {
137
+ const association = collection.model.associations[target];
138
+ if (association) {
139
+ includeOptions = {
140
+ ...includeOptions,
141
+ ...association.generateInclude()
142
+ };
143
+ }
144
+ }
145
+ return includeOptions;
146
+ });
147
+ const filterParser = new import_filter_parser.default(options.filter, { collection });
148
+ const { where, include: filterInclude } = filterParser.toSequelizeParams();
149
+ if (filterInclude) {
150
+ const stack = [...filterInclude];
151
+ while (stack.length) {
152
+ const item = stack.pop();
153
+ const parentCollection = database.getCollection(item.parentCollection || collection.name);
154
+ const field = parentCollection.fields.get(item.association);
155
+ if ((field == null ? void 0 : field.type) === "belongsToMany") {
156
+ item.through = { attributes: [] };
157
+ }
158
+ if ((field == null ? void 0 : field.target) && ((_a = item.include) == null ? void 0 : _a.length)) {
159
+ for (const child of item.include) {
160
+ child.parentCollection = field.target;
161
+ stack.push(child);
162
+ }
163
+ }
164
+ }
165
+ }
166
+ let hasAgg = false;
167
+ const attributes = [];
168
+ const fieldMap = {};
169
+ const projectedFieldMap = {};
170
+ measures.forEach((measure) => {
171
+ const { field, aggregation, alias, distinct } = measure;
172
+ const col = sequelize.col(field);
173
+ const attribute = [];
174
+ if (aggregation) {
175
+ if (!ALLOWED_AGG_FUNCS.includes(aggregation)) {
176
+ throw new Error(`Invalid aggregation function: ${aggregation}`);
177
+ }
178
+ hasAgg = true;
179
+ attribute.push(sequelize.fn(aggregation, distinct ? sequelize.fn("DISTINCT", col) : col));
180
+ } else {
181
+ attribute.push(col);
182
+ }
183
+ if (alias) {
184
+ attribute.push(alias);
185
+ }
186
+ attributes.push(attribute.length > 1 ? attribute : attribute[0]);
187
+ fieldMap[alias || field] = measure;
188
+ projectedFieldMap[alias || field] = attribute[0];
189
+ });
190
+ const group = [];
191
+ dimensions.forEach((dimension) => {
192
+ const { field, format, alias, type, options: fieldOptions } = dimension;
193
+ const attribute = [];
194
+ if (format) {
195
+ attribute.push(formatter.format({ type, field, format, timezone: options.timezone, fieldOptions }));
196
+ } else {
197
+ attribute.push(sequelize.col(field));
198
+ }
199
+ if (alias) {
200
+ attribute.push(alias);
201
+ }
202
+ attributes.push(attribute.length > 1 ? attribute : attribute[0]);
203
+ if (hasAgg) {
204
+ group.push(attribute[0]);
205
+ }
206
+ fieldMap[alias || field] = dimension;
207
+ projectedFieldMap[alias || field] = attribute[0];
208
+ });
209
+ const order = orders.map((item) => {
210
+ var _a2;
211
+ const alias = sequelize.getQueryInterface().quoteIdentifier(item.alias);
212
+ const projectedField = projectedFieldMap[item.alias] || projectedFieldMap[item.name] || projectedFieldMap[item.field];
213
+ const name = hasAgg ? projectedField || sequelize.literal(alias) : sequelize.col(item.field);
214
+ let sort = ALLOWED_ORDER_DIRECTIONS.includes((_a2 = item.order) == null ? void 0 : _a2.toUpperCase()) ? item.order.toUpperCase() : "ASC";
215
+ if (item.nulls === "first") {
216
+ sort += " NULLS FIRST";
217
+ }
218
+ if (item.nulls === "last") {
219
+ sort += " NULLS LAST";
220
+ }
221
+ return [name, sort];
222
+ });
223
+ const queryOptions = {
224
+ where,
225
+ having: (0, import_having.buildHaving)(database, formatter, fieldMap, options.having, options.timezone),
226
+ attributes,
227
+ include: [...include, ...filterInclude || []],
228
+ group,
229
+ order,
230
+ subQuery: false,
231
+ raw: true
232
+ };
233
+ if (!hasAgg || dimensions.length) {
234
+ queryOptions.limit = options.limit || 2e3;
235
+ queryOptions.offset = options.offset || 0;
236
+ }
237
+ return { queryOptions, fieldMap };
238
+ }
239
+ __name(buildQuery, "buildQuery");
240
+ function normalizeQueryResult(data, fieldMap) {
241
+ const dateTimeTypes = ["date", "datetime", "datetimeTz", "datetimeNoTz"];
242
+ return data.map((record) => {
243
+ Object.entries(record).forEach(([key, value]) => {
244
+ if (value === null || value === void 0) {
245
+ return;
246
+ }
247
+ const field = fieldMap[key];
248
+ const type = field == null ? void 0 : field.type;
249
+ if (["bigInt", "integer", "float", "double", "decimal"].includes(type)) {
250
+ record[key] = Number(value);
251
+ return;
252
+ }
253
+ if (!(field == null ? void 0 : field.format) && dateTimeTypes.includes(type) && !(value instanceof Date)) {
254
+ const dateValue = new Date(value);
255
+ if (!Number.isNaN(dateValue.getTime())) {
256
+ record[key] = dateValue;
257
+ }
258
+ }
259
+ });
260
+ return record;
261
+ });
262
+ }
263
+ __name(normalizeQueryResult, "normalizeQueryResult");
264
+ // Annotate the CommonJS export names for ESM import in node:
265
+ 0 && (module.exports = {
266
+ buildQuery,
267
+ normalizeQueryResult
268
+ });