@514labs/moose-lib 0.6.514 → 0.6.515

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.
@@ -1,4 +1,4 @@
1
- import { a0 as TypedBase, O as OlapTable, L as LifeCycle, a1 as Column, $ as QueryClient, K as sql, a2 as RowPolicyOptions, R as RawValue, M as Sql, a as OlapConfig, a3 as TypiaValidators, V as View, C as ClickHouseEngines } from './view-CJKyTLjp.mjs';
1
+ import { a0 as TypedBase, O as OlapTable, L as LifeCycle, a1 as Column, $ as QueryClient, K as sql, a2 as RowPolicyOptions, R as RawValue, M as Sql, a as OlapConfig, a3 as TypiaValidators, V as View, C as ClickHouseEngines } from './view-BCWJcLF6.js';
2
2
  import { IJsonSchemaCollection } from 'typia';
3
3
  import { Client } from '@temporalio/client';
4
4
  import { JWTPayload } from 'jose';
@@ -1247,9 +1247,10 @@ declare function getViews(): Map<string, View>;
1247
1247
  /**
1248
1248
  * Get a registered view by name.
1249
1249
  * @param name - The name of the view
1250
+ * @param database - Optional database the view belongs to (for multi-database setups)
1250
1251
  * @returns The View instance or undefined if not found
1251
1252
  */
1252
- declare function getView(name: string): View | undefined;
1253
+ declare function getView(name: string, database?: string): View | undefined;
1253
1254
  /**
1254
1255
  * Get all registered row policies.
1255
1256
  * @returns A Map of policy name to SelectRowPolicy instance
@@ -1,4 +1,4 @@
1
- import { a0 as TypedBase, O as OlapTable, L as LifeCycle, a1 as Column, $ as QueryClient, K as sql, a2 as RowPolicyOptions, R as RawValue, M as Sql, a as OlapConfig, a3 as TypiaValidators, V as View, C as ClickHouseEngines } from './view-CJKyTLjp.js';
1
+ import { a0 as TypedBase, O as OlapTable, L as LifeCycle, a1 as Column, $ as QueryClient, K as sql, a2 as RowPolicyOptions, R as RawValue, M as Sql, a as OlapConfig, a3 as TypiaValidators, V as View, C as ClickHouseEngines } from './view-BCWJcLF6.mjs';
2
2
  import { IJsonSchemaCollection } from 'typia';
3
3
  import { Client } from '@temporalio/client';
4
4
  import { JWTPayload } from 'jose';
@@ -1247,9 +1247,10 @@ declare function getViews(): Map<string, View>;
1247
1247
  /**
1248
1248
  * Get a registered view by name.
1249
1249
  * @param name - The name of the view
1250
+ * @param database - Optional database the view belongs to (for multi-database setups)
1250
1251
  * @returns The View instance or undefined if not found
1251
1252
  */
1252
- declare function getView(name: string): View | undefined;
1253
+ declare function getView(name: string, database?: string): View | undefined;
1253
1254
  /**
1254
1255
  * Get all registered row policies.
1255
1256
  * @returns A Map of policy name to SelectRowPolicy instance
package/dist/index.d.mts CHANGED
@@ -1,11 +1,11 @@
1
1
  export { JWT, Key } from './browserCompatible.mjs';
2
2
  import * as _clickhouse_client from '@clickhouse/client';
3
3
  import { KafkaJS } from '@514labs/kafka-javascript';
4
- import { V as MooseUtils, X as MooseClient, M as MaterializedView } from './index-BCTJXoD8.mjs';
5
- export { A as Aggregated, f as Api, g as ApiConfig, a3 as ApiHelpers, R as ApiUtil, C as ConsumptionApi, a4 as ConsumptionHelpers, U as ConsumptionUtil, c as DeadLetter, D as DeadLetterModel, d as DeadLetterQueue, l as ETLPipeline, m as ETLPipelineConfig, E as EgressConfig, F as FrameworkApp, I as IngestApi, e as IngestConfig, h as IngestPipeline, Y as MOOSE_RLS_ROLE, _ as MOOSE_RLS_SETTING_PREFIX, Z as MOOSE_RLS_USER, $ as RowPoliciesConfig, j as SelectRowPolicy, k as SelectRowPolicyConfig, S as SimpleAggregated, i as SqlResource, a as Stream, b as StreamConfig, T as Task, n as WebApp, o as WebAppConfig, p as WebAppHandler, W as Workflow, a1 as WorkflowClient, a0 as buildRowPolicyOptionsFromClaims, x as getApi, w as getApis, v as getIngestApi, u as getIngestApis, N as getMaterializedView, O as getMaterializedViews, P as getSelectRowPolicies, Q as getSelectRowPolicy, z as getSqlResource, y as getSqlResources, t as getStream, s as getStreams, r as getTable, q as getTables, a2 as getTemporalClient, K as getView, L as getViews, J as getWebApp, H as getWebApps, G as getWorkflow, B as getWorkflows, a5 as joinQueries } from './index-BCTJXoD8.mjs';
4
+ import { V as MooseUtils, X as MooseClient, M as MaterializedView } from './index-k_kpRxE3.mjs';
5
+ export { A as Aggregated, f as Api, g as ApiConfig, a3 as ApiHelpers, R as ApiUtil, C as ConsumptionApi, a4 as ConsumptionHelpers, U as ConsumptionUtil, c as DeadLetter, D as DeadLetterModel, d as DeadLetterQueue, l as ETLPipeline, m as ETLPipelineConfig, E as EgressConfig, F as FrameworkApp, I as IngestApi, e as IngestConfig, h as IngestPipeline, Y as MOOSE_RLS_ROLE, _ as MOOSE_RLS_SETTING_PREFIX, Z as MOOSE_RLS_USER, $ as RowPoliciesConfig, j as SelectRowPolicy, k as SelectRowPolicyConfig, S as SimpleAggregated, i as SqlResource, a as Stream, b as StreamConfig, T as Task, n as WebApp, o as WebAppConfig, p as WebAppHandler, W as Workflow, a1 as WorkflowClient, a0 as buildRowPolicyOptionsFromClaims, x as getApi, w as getApis, v as getIngestApi, u as getIngestApis, N as getMaterializedView, O as getMaterializedViews, P as getSelectRowPolicies, Q as getSelectRowPolicy, z as getSqlResource, y as getSqlResources, t as getStream, s as getStreams, r as getTable, q as getTables, a2 as getTemporalClient, K as getView, L as getViews, J as getWebApp, H as getWebApps, G as getWorkflow, B as getWorkflows, a5 as joinQueries } from './index-k_kpRxE3.mjs';
6
6
  import http from 'http';
7
- import { M as Sql, O as OlapTable, a1 as Column, $ as QueryClient, a4 as DataType } from './view-CJKyTLjp.mjs';
8
- export { n as ClickHouseAlias, d as ClickHouseByteSize, o as ClickHouseCodec, c as ClickHouseDecimal, k as ClickHouseDefault, C as ClickHouseEngines, e as ClickHouseFixedStringSize, f as ClickHouseFloat, g as ClickHouseInt, h as ClickHouseJson, a7 as ClickHouseLineString, m as ClickHouseMaterialized, a8 as ClickHouseMultiLineString, aa as ClickHouseMultiPolygon, j as ClickHouseNamedTuple, a5 as ClickHousePoint, a9 as ClickHousePolygon, b as ClickHousePrecision, a6 as ClickHouseRing, l as ClickHouseTTL, D as DateTime, p as DateTime64, r as DateTime64String, q as DateTimeString, A as Decimal, F as FixedString, s as Float32, t as Float64, G as IdentifierBrandedString, B as Insertable, u as Int16, v as Int32, w as Int64, I as Int8, L as LifeCycle, i as LowCardinality, N as NonIdentifierBrandedString, a as OlapConfig, R as RawValue, a2 as RowPolicyOptions, S as S3QueueTableSettings, J as SqlTemplateTag, T as TableConstraint, x as UInt16, y as UInt32, z as UInt64, U as UInt8, H as Value, V as View, W as WithDefault, Z as createClickhouseParameter, Y as getValueFromParameter, _ as mapToClickHouseType, E as quoteIdentifier, K as sql, Q as toQuery, X as toQueryPreview, P as toStaticQuery } from './view-CJKyTLjp.mjs';
7
+ import { M as Sql, O as OlapTable, a1 as Column, $ as QueryClient, a5 as DataType } from './view-BCWJcLF6.mjs';
8
+ export { n as ClickHouseAlias, d as ClickHouseByteSize, o as ClickHouseCodec, c as ClickHouseDecimal, k as ClickHouseDefault, C as ClickHouseEngines, e as ClickHouseFixedStringSize, f as ClickHouseFloat, g as ClickHouseInt, h as ClickHouseJson, a8 as ClickHouseLineString, m as ClickHouseMaterialized, a9 as ClickHouseMultiLineString, ab as ClickHouseMultiPolygon, j as ClickHouseNamedTuple, a6 as ClickHousePoint, aa as ClickHousePolygon, b as ClickHousePrecision, a7 as ClickHouseRing, l as ClickHouseTTL, D as DateTime, p as DateTime64, r as DateTime64String, q as DateTimeString, A as Decimal, F as FixedString, s as Float32, t as Float64, G as IdentifierBrandedString, B as Insertable, u as Int16, v as Int32, w as Int64, I as Int8, L as LifeCycle, i as LowCardinality, N as NonIdentifierBrandedString, a as OlapConfig, R as RawValue, a2 as RowPolicyOptions, S as S3QueueTableSettings, J as SqlTemplateTag, T as TableConstraint, x as UInt16, y as UInt32, z as UInt64, U as UInt8, H as Value, V as View, W as WithDefault, Z as createClickhouseParameter, Y as getValueFromParameter, _ as mapToClickHouseType, E as quoteIdentifier, K as sql, Q as toQuery, X as toQueryPreview, P as toStaticQuery } from './view-BCWJcLF6.mjs';
9
9
  import { IsTuple } from 'typia/lib/typings/IsTuple';
10
10
  import { Readable } from 'node:stream';
11
11
  import { z } from 'zod';
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  export { JWT, Key } from './browserCompatible.js';
2
2
  import * as _clickhouse_client from '@clickhouse/client';
3
3
  import { KafkaJS } from '@514labs/kafka-javascript';
4
- import { V as MooseUtils, X as MooseClient, M as MaterializedView } from './index-BOIsE8xN.js';
5
- export { A as Aggregated, f as Api, g as ApiConfig, a3 as ApiHelpers, R as ApiUtil, C as ConsumptionApi, a4 as ConsumptionHelpers, U as ConsumptionUtil, c as DeadLetter, D as DeadLetterModel, d as DeadLetterQueue, l as ETLPipeline, m as ETLPipelineConfig, E as EgressConfig, F as FrameworkApp, I as IngestApi, e as IngestConfig, h as IngestPipeline, Y as MOOSE_RLS_ROLE, _ as MOOSE_RLS_SETTING_PREFIX, Z as MOOSE_RLS_USER, $ as RowPoliciesConfig, j as SelectRowPolicy, k as SelectRowPolicyConfig, S as SimpleAggregated, i as SqlResource, a as Stream, b as StreamConfig, T as Task, n as WebApp, o as WebAppConfig, p as WebAppHandler, W as Workflow, a1 as WorkflowClient, a0 as buildRowPolicyOptionsFromClaims, x as getApi, w as getApis, v as getIngestApi, u as getIngestApis, N as getMaterializedView, O as getMaterializedViews, P as getSelectRowPolicies, Q as getSelectRowPolicy, z as getSqlResource, y as getSqlResources, t as getStream, s as getStreams, r as getTable, q as getTables, a2 as getTemporalClient, K as getView, L as getViews, J as getWebApp, H as getWebApps, G as getWorkflow, B as getWorkflows, a5 as joinQueries } from './index-BOIsE8xN.js';
4
+ import { V as MooseUtils, X as MooseClient, M as MaterializedView } from './index-7uxZbwmY.js';
5
+ export { A as Aggregated, f as Api, g as ApiConfig, a3 as ApiHelpers, R as ApiUtil, C as ConsumptionApi, a4 as ConsumptionHelpers, U as ConsumptionUtil, c as DeadLetter, D as DeadLetterModel, d as DeadLetterQueue, l as ETLPipeline, m as ETLPipelineConfig, E as EgressConfig, F as FrameworkApp, I as IngestApi, e as IngestConfig, h as IngestPipeline, Y as MOOSE_RLS_ROLE, _ as MOOSE_RLS_SETTING_PREFIX, Z as MOOSE_RLS_USER, $ as RowPoliciesConfig, j as SelectRowPolicy, k as SelectRowPolicyConfig, S as SimpleAggregated, i as SqlResource, a as Stream, b as StreamConfig, T as Task, n as WebApp, o as WebAppConfig, p as WebAppHandler, W as Workflow, a1 as WorkflowClient, a0 as buildRowPolicyOptionsFromClaims, x as getApi, w as getApis, v as getIngestApi, u as getIngestApis, N as getMaterializedView, O as getMaterializedViews, P as getSelectRowPolicies, Q as getSelectRowPolicy, z as getSqlResource, y as getSqlResources, t as getStream, s as getStreams, r as getTable, q as getTables, a2 as getTemporalClient, K as getView, L as getViews, J as getWebApp, H as getWebApps, G as getWorkflow, B as getWorkflows, a5 as joinQueries } from './index-7uxZbwmY.js';
6
6
  import http from 'http';
7
- import { M as Sql, O as OlapTable, a1 as Column, $ as QueryClient, a4 as DataType } from './view-CJKyTLjp.js';
8
- export { n as ClickHouseAlias, d as ClickHouseByteSize, o as ClickHouseCodec, c as ClickHouseDecimal, k as ClickHouseDefault, C as ClickHouseEngines, e as ClickHouseFixedStringSize, f as ClickHouseFloat, g as ClickHouseInt, h as ClickHouseJson, a7 as ClickHouseLineString, m as ClickHouseMaterialized, a8 as ClickHouseMultiLineString, aa as ClickHouseMultiPolygon, j as ClickHouseNamedTuple, a5 as ClickHousePoint, a9 as ClickHousePolygon, b as ClickHousePrecision, a6 as ClickHouseRing, l as ClickHouseTTL, D as DateTime, p as DateTime64, r as DateTime64String, q as DateTimeString, A as Decimal, F as FixedString, s as Float32, t as Float64, G as IdentifierBrandedString, B as Insertable, u as Int16, v as Int32, w as Int64, I as Int8, L as LifeCycle, i as LowCardinality, N as NonIdentifierBrandedString, a as OlapConfig, R as RawValue, a2 as RowPolicyOptions, S as S3QueueTableSettings, J as SqlTemplateTag, T as TableConstraint, x as UInt16, y as UInt32, z as UInt64, U as UInt8, H as Value, V as View, W as WithDefault, Z as createClickhouseParameter, Y as getValueFromParameter, _ as mapToClickHouseType, E as quoteIdentifier, K as sql, Q as toQuery, X as toQueryPreview, P as toStaticQuery } from './view-CJKyTLjp.js';
7
+ import { M as Sql, O as OlapTable, a1 as Column, $ as QueryClient, a5 as DataType } from './view-BCWJcLF6.js';
8
+ export { n as ClickHouseAlias, d as ClickHouseByteSize, o as ClickHouseCodec, c as ClickHouseDecimal, k as ClickHouseDefault, C as ClickHouseEngines, e as ClickHouseFixedStringSize, f as ClickHouseFloat, g as ClickHouseInt, h as ClickHouseJson, a8 as ClickHouseLineString, m as ClickHouseMaterialized, a9 as ClickHouseMultiLineString, ab as ClickHouseMultiPolygon, j as ClickHouseNamedTuple, a6 as ClickHousePoint, aa as ClickHousePolygon, b as ClickHousePrecision, a7 as ClickHouseRing, l as ClickHouseTTL, D as DateTime, p as DateTime64, r as DateTime64String, q as DateTimeString, A as Decimal, F as FixedString, s as Float32, t as Float64, G as IdentifierBrandedString, B as Insertable, u as Int16, v as Int32, w as Int64, I as Int8, L as LifeCycle, i as LowCardinality, N as NonIdentifierBrandedString, a as OlapConfig, R as RawValue, a2 as RowPolicyOptions, S as S3QueueTableSettings, J as SqlTemplateTag, T as TableConstraint, x as UInt16, y as UInt32, z as UInt64, U as UInt8, H as Value, V as View, W as WithDefault, Z as createClickhouseParameter, Y as getValueFromParameter, _ as mapToClickHouseType, E as quoteIdentifier, K as sql, Q as toQuery, X as toQueryPreview, P as toStaticQuery } from './view-BCWJcLF6.js';
9
9
  import { IsTuple } from 'typia/lib/typings/IsTuple';
10
10
  import { Readable } from 'node:stream';
11
11
  import { z } from 'zod';
package/dist/index.js CHANGED
@@ -785,6 +785,260 @@ var import_process = __toESM(require("process"));
785
785
  var path4 = __toESM(require("path"));
786
786
  init_commons();
787
787
 
788
+ // src/sqlHelpers.ts
789
+ var quoteIdentifier = (name) => {
790
+ return name.startsWith("`") && name.endsWith("`") ? name : `\`${name}\``;
791
+ };
792
+ var isTable = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "OlapTable";
793
+ var isView = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "View";
794
+ var isColumn = (value) => typeof value === "object" && value !== null && !("kind" in value) && "name" in value && "annotations" in value;
795
+ function sqlImpl(strings, ...values) {
796
+ return new Sql(strings, values);
797
+ }
798
+ var sql = sqlImpl;
799
+ sql.statement = function(strings, ...values) {
800
+ return new Sql(strings, values, false);
801
+ };
802
+ sql.fragment = function(strings, ...values) {
803
+ return new Sql(strings, values, true);
804
+ };
805
+ var instanceofSql = (value) => typeof value === "object" && "values" in value && "strings" in value;
806
+ var Sql = class _Sql {
807
+ values;
808
+ strings;
809
+ isFragment;
810
+ constructor(rawStrings, rawValues, isFragment) {
811
+ if (rawStrings.length - 1 !== rawValues.length) {
812
+ if (rawStrings.length === 0) {
813
+ throw new TypeError("Expected at least 1 string");
814
+ }
815
+ throw new TypeError(
816
+ `Expected ${rawStrings.length} strings to have ${rawStrings.length - 1} values`
817
+ );
818
+ }
819
+ const valuesLength = rawValues.reduce(
820
+ (len, value) => len + (instanceofSql(value) ? value.values.length : isColumn(value) || isTable(value) || isView(value) ? 0 : 1),
821
+ 0
822
+ );
823
+ this.values = new Array(valuesLength);
824
+ this.strings = new Array(valuesLength + 1);
825
+ this.isFragment = isFragment;
826
+ this.strings[0] = rawStrings[0];
827
+ let i = 0, pos = 0;
828
+ while (i < rawValues.length) {
829
+ const child = rawValues[i++];
830
+ const rawString = rawStrings[i];
831
+ if (instanceofSql(child)) {
832
+ this.strings[pos] += child.strings[0];
833
+ let childIndex = 0;
834
+ while (childIndex < child.values.length) {
835
+ this.values[pos++] = child.values[childIndex++];
836
+ this.strings[pos] = child.strings[childIndex];
837
+ }
838
+ this.strings[pos] += rawString;
839
+ } else if (isColumn(child)) {
840
+ const aggregationFunction = child.annotations.find(
841
+ ([k, _]) => k === "aggregationFunction"
842
+ );
843
+ if (aggregationFunction !== void 0) {
844
+ const funcName = aggregationFunction[1].functionName;
845
+ const parenIdx = funcName.indexOf("(");
846
+ const mergedName = parenIdx !== -1 ? `${funcName.slice(0, parenIdx)}Merge${funcName.slice(parenIdx)}` : `${funcName}Merge`;
847
+ this.strings[pos] += `${mergedName}(\`${child.name}\`)`;
848
+ } else {
849
+ this.strings[pos] += `\`${child.name}\``;
850
+ }
851
+ this.strings[pos] += rawString;
852
+ } else if (isTable(child)) {
853
+ const deployedName = child.generateTableName();
854
+ if (child.config.database) {
855
+ this.strings[pos] += `\`${child.config.database}\`.\`${deployedName}\``;
856
+ } else {
857
+ this.strings[pos] += `\`${deployedName}\``;
858
+ }
859
+ this.strings[pos] += rawString;
860
+ } else if (isView(child)) {
861
+ if (child.database) {
862
+ this.strings[pos] += `\`${child.database}\`.\`${child.name}\``;
863
+ } else {
864
+ this.strings[pos] += `\`${child.name}\``;
865
+ }
866
+ this.strings[pos] += rawString;
867
+ } else {
868
+ this.values[pos++] = child;
869
+ this.strings[pos] = rawString;
870
+ }
871
+ }
872
+ }
873
+ /**
874
+ * Append another Sql fragment, returning a new Sql instance.
875
+ */
876
+ append(other) {
877
+ return new _Sql(
878
+ [...this.strings, ""],
879
+ [...this.values, other],
880
+ this.isFragment
881
+ );
882
+ }
883
+ };
884
+ sql.join = function(fragments, separator) {
885
+ if (fragments.length === 0) return new Sql([""], [], true);
886
+ if (fragments.length === 1) {
887
+ const frag = fragments[0];
888
+ return new Sql(frag.strings, frag.values, true);
889
+ }
890
+ const sep = separator ?? ", ";
891
+ const normalized = sep.includes(" ") ? sep : ` ${sep} `;
892
+ const strings = ["", ...Array(fragments.length - 1).fill(normalized), ""];
893
+ return new Sql(strings, fragments, true);
894
+ };
895
+ sql.raw = function(text) {
896
+ return new Sql([text], [], true);
897
+ };
898
+ var toStaticQuery = (sql3) => {
899
+ const [query, params] = toQuery(sql3);
900
+ if (Object.keys(params).length !== 0) {
901
+ throw new Error(
902
+ "Dynamic SQL is not allowed in the select statement in view creation."
903
+ );
904
+ }
905
+ return query;
906
+ };
907
+ var toQuery = (sql3) => {
908
+ const parameterizedStubs = sql3.values.map(
909
+ (v, i) => createClickhouseParameter(i, v)
910
+ );
911
+ const query = sql3.strings.map(
912
+ (s, i) => s != "" ? `${s}${emptyIfUndefined(parameterizedStubs[i])}` : ""
913
+ ).join("");
914
+ const query_params = sql3.values.reduce(
915
+ (acc, v, i) => ({
916
+ ...acc,
917
+ [`p${i}`]: getValueFromParameter(v)
918
+ }),
919
+ {}
920
+ );
921
+ return [query, query_params];
922
+ };
923
+ var toQueryPreview = (sql3) => {
924
+ try {
925
+ const formatValue = (v) => {
926
+ if (Array.isArray(v)) {
927
+ const [type, val] = v;
928
+ if (type === "Identifier") {
929
+ return `\`${String(val)}\``;
930
+ }
931
+ return `[${v.map((x) => formatValue(x)).join(", ")}]`;
932
+ }
933
+ if (v === null || v === void 0) return "NULL";
934
+ if (typeof v === "string") return `'${v.replace(/'/g, "''")}'`;
935
+ if (typeof v === "number") return String(v);
936
+ if (typeof v === "boolean") return v ? "true" : "false";
937
+ if (v instanceof Date)
938
+ return `'${v.toISOString().replace("T", " ").slice(0, 19)}'`;
939
+ try {
940
+ return JSON.stringify(v);
941
+ } catch {
942
+ return String(v);
943
+ }
944
+ };
945
+ let out = sql3.strings[0] ?? "";
946
+ for (let i = 0; i < sql3.values.length; i++) {
947
+ const val = getValueFromParameter(sql3.values[i]);
948
+ out += formatValue(val);
949
+ out += sql3.strings[i + 1] ?? "";
950
+ }
951
+ return out.replace(/\s+/g, " ").trim();
952
+ } catch (error) {
953
+ console.log(`toQueryPreview error: ${error}`);
954
+ return "/* query preview unavailable */";
955
+ }
956
+ };
957
+ var getValueFromParameter = (value) => {
958
+ if (Array.isArray(value)) {
959
+ const [type, val] = value;
960
+ if (type === "Identifier") return val;
961
+ }
962
+ return value;
963
+ };
964
+ function createClickhouseParameter(parameterIndex, value) {
965
+ return `{p${parameterIndex}:${mapToClickHouseType(value)}}`;
966
+ }
967
+ var mapToClickHouseType = (value) => {
968
+ if (typeof value === "number") {
969
+ return Number.isInteger(value) ? "Int" : "Float";
970
+ }
971
+ if (typeof value === "boolean") return "Bool";
972
+ if (value instanceof Date) return "DateTime";
973
+ if (Array.isArray(value)) {
974
+ const [type, _] = value;
975
+ return type;
976
+ }
977
+ return "String";
978
+ };
979
+ function emptyIfUndefined(value) {
980
+ return value === void 0 ? "" : value;
981
+ }
982
+
983
+ // src/dmv2/sdk/tableReferenceUtils.ts
984
+ function formatTableReference(table) {
985
+ const database = table instanceof OlapTable ? table.config.database : table.database;
986
+ const deployedName = table instanceof OlapTable ? table.generateTableName() : table.name;
987
+ if (database) {
988
+ return `\`${database}\`.\`${deployedName}\``;
989
+ }
990
+ return `\`${deployedName}\``;
991
+ }
992
+
993
+ // src/dmv2/sdk/view.ts
994
+ function viewRegistryKey(database, name) {
995
+ return database ? `${database}::${name}` : name;
996
+ }
997
+ var View = class {
998
+ /** @internal */
999
+ kind = "View";
1000
+ /** The name of the view */
1001
+ name;
1002
+ /** Optional database where the view is created. When set, the view is created as `database`.`name` in ClickHouse. */
1003
+ database;
1004
+ /** The SELECT SQL statement that defines the view */
1005
+ selectSql;
1006
+ /** Names of source tables/views that the SELECT reads from */
1007
+ sourceTables;
1008
+ /** Optional metadata for the view */
1009
+ metadata;
1010
+ constructor(name, configOrSelectStatement, baseTables, metadata) {
1011
+ const config = typeof configOrSelectStatement === "object" && configOrSelectStatement !== null && "selectStatement" in configOrSelectStatement && "baseTables" in configOrSelectStatement ? configOrSelectStatement : {
1012
+ selectStatement: configOrSelectStatement,
1013
+ baseTables: baseTables ?? [],
1014
+ metadata
1015
+ };
1016
+ let selectStatement = config.selectStatement;
1017
+ if (typeof selectStatement !== "string") {
1018
+ selectStatement = toStaticQuery(selectStatement);
1019
+ }
1020
+ this.name = name;
1021
+ this.database = config.database;
1022
+ this.selectSql = selectStatement;
1023
+ this.sourceTables = config.baseTables.map((t) => formatTableReference(t));
1024
+ this.metadata = config.metadata ? { ...config.metadata } : {};
1025
+ if (!this.metadata.source) {
1026
+ const stack = new Error().stack;
1027
+ const sourceInfo = getSourceFileFromStack(stack);
1028
+ if (sourceInfo) {
1029
+ this.metadata.source = { file: sourceInfo };
1030
+ }
1031
+ }
1032
+ const views = getMooseInternal().views;
1033
+ const registryKey = viewRegistryKey(this.database, this.name);
1034
+ if (!isClientOnlyMode() && views.has(registryKey)) {
1035
+ const qualifiedName = this.database ? `${this.database}.${this.name}` : this.name;
1036
+ throw new Error(`View with name ${qualifiedName} already exists`);
1037
+ }
1038
+ views.set(registryKey, this);
1039
+ }
1040
+ };
1041
+
788
1042
  // src/compiler-config.ts
789
1043
  var import_fs2 = require("fs");
790
1044
  var import_path2 = __toESM(require("path"));
@@ -1190,199 +1444,6 @@ var getWorkflows = async () => {
1190
1444
  // src/dmv2/sdk/olapTable.ts
1191
1445
  var import_node_stream = require("stream");
1192
1446
  var import_node_crypto = require("crypto");
1193
-
1194
- // src/sqlHelpers.ts
1195
- var quoteIdentifier = (name) => {
1196
- return name.startsWith("`") && name.endsWith("`") ? name : `\`${name}\``;
1197
- };
1198
- var isTable = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "OlapTable";
1199
- var isView = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "View";
1200
- var isColumn = (value) => typeof value === "object" && value !== null && !("kind" in value) && "name" in value && "annotations" in value;
1201
- function sqlImpl(strings, ...values) {
1202
- return new Sql(strings, values);
1203
- }
1204
- var sql = sqlImpl;
1205
- sql.statement = function(strings, ...values) {
1206
- return new Sql(strings, values, false);
1207
- };
1208
- sql.fragment = function(strings, ...values) {
1209
- return new Sql(strings, values, true);
1210
- };
1211
- var instanceofSql = (value) => typeof value === "object" && "values" in value && "strings" in value;
1212
- var Sql = class _Sql {
1213
- values;
1214
- strings;
1215
- isFragment;
1216
- constructor(rawStrings, rawValues, isFragment) {
1217
- if (rawStrings.length - 1 !== rawValues.length) {
1218
- if (rawStrings.length === 0) {
1219
- throw new TypeError("Expected at least 1 string");
1220
- }
1221
- throw new TypeError(
1222
- `Expected ${rawStrings.length} strings to have ${rawStrings.length - 1} values`
1223
- );
1224
- }
1225
- const valuesLength = rawValues.reduce(
1226
- (len, value) => len + (instanceofSql(value) ? value.values.length : isColumn(value) || isTable(value) || isView(value) ? 0 : 1),
1227
- 0
1228
- );
1229
- this.values = new Array(valuesLength);
1230
- this.strings = new Array(valuesLength + 1);
1231
- this.isFragment = isFragment;
1232
- this.strings[0] = rawStrings[0];
1233
- let i = 0, pos = 0;
1234
- while (i < rawValues.length) {
1235
- const child = rawValues[i++];
1236
- const rawString = rawStrings[i];
1237
- if (instanceofSql(child)) {
1238
- this.strings[pos] += child.strings[0];
1239
- let childIndex = 0;
1240
- while (childIndex < child.values.length) {
1241
- this.values[pos++] = child.values[childIndex++];
1242
- this.strings[pos] = child.strings[childIndex];
1243
- }
1244
- this.strings[pos] += rawString;
1245
- } else if (isColumn(child)) {
1246
- const aggregationFunction = child.annotations.find(
1247
- ([k, _]) => k === "aggregationFunction"
1248
- );
1249
- if (aggregationFunction !== void 0) {
1250
- const funcName = aggregationFunction[1].functionName;
1251
- const parenIdx = funcName.indexOf("(");
1252
- const mergedName = parenIdx !== -1 ? `${funcName.slice(0, parenIdx)}Merge${funcName.slice(parenIdx)}` : `${funcName}Merge`;
1253
- this.strings[pos] += `${mergedName}(\`${child.name}\`)`;
1254
- } else {
1255
- this.strings[pos] += `\`${child.name}\``;
1256
- }
1257
- this.strings[pos] += rawString;
1258
- } else if (isTable(child)) {
1259
- const deployedName = child.generateTableName();
1260
- if (child.config.database) {
1261
- this.strings[pos] += `\`${child.config.database}\`.\`${deployedName}\``;
1262
- } else {
1263
- this.strings[pos] += `\`${deployedName}\``;
1264
- }
1265
- this.strings[pos] += rawString;
1266
- } else if (isView(child)) {
1267
- this.strings[pos] += `\`${child.name}\``;
1268
- this.strings[pos] += rawString;
1269
- } else {
1270
- this.values[pos++] = child;
1271
- this.strings[pos] = rawString;
1272
- }
1273
- }
1274
- }
1275
- /**
1276
- * Append another Sql fragment, returning a new Sql instance.
1277
- */
1278
- append(other) {
1279
- return new _Sql(
1280
- [...this.strings, ""],
1281
- [...this.values, other],
1282
- this.isFragment
1283
- );
1284
- }
1285
- };
1286
- sql.join = function(fragments, separator) {
1287
- if (fragments.length === 0) return new Sql([""], [], true);
1288
- if (fragments.length === 1) {
1289
- const frag = fragments[0];
1290
- return new Sql(frag.strings, frag.values, true);
1291
- }
1292
- const sep = separator ?? ", ";
1293
- const normalized = sep.includes(" ") ? sep : ` ${sep} `;
1294
- const strings = ["", ...Array(fragments.length - 1).fill(normalized), ""];
1295
- return new Sql(strings, fragments, true);
1296
- };
1297
- sql.raw = function(text) {
1298
- return new Sql([text], [], true);
1299
- };
1300
- var toStaticQuery = (sql3) => {
1301
- const [query, params] = toQuery(sql3);
1302
- if (Object.keys(params).length !== 0) {
1303
- throw new Error(
1304
- "Dynamic SQL is not allowed in the select statement in view creation."
1305
- );
1306
- }
1307
- return query;
1308
- };
1309
- var toQuery = (sql3) => {
1310
- const parameterizedStubs = sql3.values.map(
1311
- (v, i) => createClickhouseParameter(i, v)
1312
- );
1313
- const query = sql3.strings.map(
1314
- (s, i) => s != "" ? `${s}${emptyIfUndefined(parameterizedStubs[i])}` : ""
1315
- ).join("");
1316
- const query_params = sql3.values.reduce(
1317
- (acc, v, i) => ({
1318
- ...acc,
1319
- [`p${i}`]: getValueFromParameter(v)
1320
- }),
1321
- {}
1322
- );
1323
- return [query, query_params];
1324
- };
1325
- var toQueryPreview = (sql3) => {
1326
- try {
1327
- const formatValue = (v) => {
1328
- if (Array.isArray(v)) {
1329
- const [type, val] = v;
1330
- if (type === "Identifier") {
1331
- return `\`${String(val)}\``;
1332
- }
1333
- return `[${v.map((x) => formatValue(x)).join(", ")}]`;
1334
- }
1335
- if (v === null || v === void 0) return "NULL";
1336
- if (typeof v === "string") return `'${v.replace(/'/g, "''")}'`;
1337
- if (typeof v === "number") return String(v);
1338
- if (typeof v === "boolean") return v ? "true" : "false";
1339
- if (v instanceof Date)
1340
- return `'${v.toISOString().replace("T", " ").slice(0, 19)}'`;
1341
- try {
1342
- return JSON.stringify(v);
1343
- } catch {
1344
- return String(v);
1345
- }
1346
- };
1347
- let out = sql3.strings[0] ?? "";
1348
- for (let i = 0; i < sql3.values.length; i++) {
1349
- const val = getValueFromParameter(sql3.values[i]);
1350
- out += formatValue(val);
1351
- out += sql3.strings[i + 1] ?? "";
1352
- }
1353
- return out.replace(/\s+/g, " ").trim();
1354
- } catch (error) {
1355
- console.log(`toQueryPreview error: ${error}`);
1356
- return "/* query preview unavailable */";
1357
- }
1358
- };
1359
- var getValueFromParameter = (value) => {
1360
- if (Array.isArray(value)) {
1361
- const [type, val] = value;
1362
- if (type === "Identifier") return val;
1363
- }
1364
- return value;
1365
- };
1366
- function createClickhouseParameter(parameterIndex, value) {
1367
- return `{p${parameterIndex}:${mapToClickHouseType(value)}}`;
1368
- }
1369
- var mapToClickHouseType = (value) => {
1370
- if (typeof value === "number") {
1371
- return Number.isInteger(value) ? "Int" : "Float";
1372
- }
1373
- if (typeof value === "boolean") return "Bool";
1374
- if (value instanceof Date) return "DateTime";
1375
- if (Array.isArray(value)) {
1376
- const [type, _] = value;
1377
- return type;
1378
- }
1379
- return "String";
1380
- };
1381
- function emptyIfUndefined(value) {
1382
- return value === void 0 ? "" : value;
1383
- }
1384
-
1385
- // src/dmv2/sdk/olapTable.ts
1386
1447
  var OlapTable = class extends TypedBase {
1387
1448
  name;
1388
1449
  /** @internal */
@@ -2943,56 +3004,6 @@ var ETLPipeline = class {
2943
3004
  }
2944
3005
  };
2945
3006
 
2946
- // src/dmv2/sdk/view.ts
2947
- function formatTableReference(table) {
2948
- const database = table instanceof OlapTable ? table.config.database : void 0;
2949
- const deployedName = table instanceof OlapTable ? table.generateTableName() : table.name;
2950
- if (database) {
2951
- return `\`${database}\`.\`${deployedName}\``;
2952
- }
2953
- return `\`${deployedName}\``;
2954
- }
2955
- var View = class {
2956
- /** @internal */
2957
- kind = "View";
2958
- /** The name of the view */
2959
- name;
2960
- /** The SELECT SQL statement that defines the view */
2961
- selectSql;
2962
- /** Names of source tables/views that the SELECT reads from */
2963
- sourceTables;
2964
- /** Optional metadata for the view */
2965
- metadata;
2966
- /**
2967
- * Creates a new View instance.
2968
- * @param name The name of the view to be created.
2969
- * @param selectStatement The SQL SELECT statement that defines the view's logic.
2970
- * @param baseTables An array of OlapTable or View objects that the `selectStatement` reads from. Used for dependency tracking.
2971
- * @param metadata Optional metadata for the view (e.g., description, source file).
2972
- */
2973
- constructor(name, selectStatement, baseTables, metadata) {
2974
- if (typeof selectStatement !== "string") {
2975
- selectStatement = toStaticQuery(selectStatement);
2976
- }
2977
- this.name = name;
2978
- this.selectSql = selectStatement;
2979
- this.sourceTables = baseTables.map((t) => formatTableReference(t));
2980
- this.metadata = metadata ? { ...metadata } : {};
2981
- if (!this.metadata.source) {
2982
- const stack = new Error().stack;
2983
- const sourceInfo = getSourceFileFromStack(stack);
2984
- if (sourceInfo) {
2985
- this.metadata.source = { file: sourceInfo };
2986
- }
2987
- }
2988
- const views = getMooseInternal().views;
2989
- if (!isClientOnlyMode() && views.has(this.name)) {
2990
- throw new Error(`View with name ${this.name} already exists`);
2991
- }
2992
- views.set(this.name, this);
2993
- }
2994
- };
2995
-
2996
3007
  // src/dmv2/sdk/materializedView.ts
2997
3008
  var requireTargetTableName = (tableName) => {
2998
3009
  if (typeof tableName === "string") {
@@ -3368,8 +3379,9 @@ function getMaterializedView(name) {
3368
3379
  function getViews() {
3369
3380
  return getMooseInternal().views;
3370
3381
  }
3371
- function getView(name) {
3372
- return getMooseInternal().views.get(name);
3382
+ function getView(name, database) {
3383
+ const key = viewRegistryKey(database, name);
3384
+ return getMooseInternal().views.get(key);
3373
3385
  }
3374
3386
  function getSelectRowPolicies() {
3375
3387
  return getMooseInternal().selectRowPolicies;