@nmakarov/cli-toolkit 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2601,8 +2601,304 @@ var FileDatabase = class {
2601
2601
  return { ...this.metadata };
2602
2602
  }
2603
2603
  };
2604
+
2605
+ // src/db/index.ts
2606
+ import knex from "knex";
2607
+ var Db = class {
2608
+ knexInstance = null;
2609
+ config;
2610
+ logger;
2611
+ queriesLog = [];
2612
+ isConnected = false;
2613
+ constructor(config2) {
2614
+ if (!config2.connectionString) {
2615
+ throw new ParamError("Db: connectionString is required");
2616
+ }
2617
+ this.config = {
2618
+ testConnection: true,
2619
+ profile: false,
2620
+ pool: { min: 2, max: 10 },
2621
+ acquireConnectionTimeout: 1e4,
2622
+ ssl: { rejectUnauthorized: false },
2623
+ logger: console,
2624
+ name: "default",
2625
+ ...config2
2626
+ };
2627
+ this.logger = this.config.logger;
2628
+ const instance2 = this;
2629
+ const callableWrapper = function(...args) {
2630
+ throw new Error("This should never be called directly");
2631
+ };
2632
+ callableWrapper._instance = instance2;
2633
+ return new Proxy(callableWrapper, {
2634
+ // Intercept function calls: db('table')
2635
+ apply: (target, thisArg, argumentsList) => {
2636
+ const inst = target._instance;
2637
+ if (!inst.knexInstance) {
2638
+ throw new Error("Db: Not connected. Call connect() first.");
2639
+ }
2640
+ return inst.knexInstance(...argumentsList);
2641
+ },
2642
+ // Intercept property access: db.schema, db.raw, etc.
2643
+ get: (target, prop) => {
2644
+ if (prop === "_instance") {
2645
+ return target._instance;
2646
+ }
2647
+ const instance3 = target._instance;
2648
+ const ownMethods = [
2649
+ "connect",
2650
+ "disconnect",
2651
+ "testConnection",
2652
+ "tableExists",
2653
+ "getQueryLog",
2654
+ "getKnex",
2655
+ "isConnectedToDb",
2656
+ "getErrorMessage",
2657
+ "detectClient",
2658
+ "attachProfiler"
2659
+ ];
2660
+ if (prop in instance3) {
2661
+ const value = instance3[prop];
2662
+ if (typeof value === "function" && ownMethods.includes(prop)) {
2663
+ return value.bind(instance3);
2664
+ }
2665
+ if (typeof value !== "function") {
2666
+ return value;
2667
+ }
2668
+ }
2669
+ if (instance3.knexInstance) {
2670
+ const knexProp = instance3.knexInstance[prop];
2671
+ if (typeof knexProp === "function") {
2672
+ return knexProp.bind(instance3.knexInstance);
2673
+ }
2674
+ return knexProp;
2675
+ }
2676
+ if (prop in instance3) {
2677
+ const method = instance3[prop];
2678
+ if (typeof method === "function") {
2679
+ return method.bind(instance3);
2680
+ }
2681
+ return method;
2682
+ }
2683
+ return void 0;
2684
+ }
2685
+ });
2686
+ }
2687
+ /**
2688
+ * Detect database client type from connection string
2689
+ */
2690
+ detectClient(connectionString) {
2691
+ if (connectionString.match(/^postgresql/)) {
2692
+ return "pg";
2693
+ }
2694
+ if (connectionString.match(/^mysql/)) {
2695
+ return "mysql2";
2696
+ }
2697
+ return null;
2698
+ }
2699
+ /**
2700
+ * Connect to the database
2701
+ */
2702
+ async connect() {
2703
+ if (this.isConnected && this.knexInstance) {
2704
+ this.logger.warn?.("[Db] Already connected");
2705
+ return;
2706
+ }
2707
+ const client = this.detectClient(this.config.connectionString);
2708
+ if (!client) {
2709
+ throw new ParamError(
2710
+ `Db: Cannot determine client type from connection string. Expected postgresql:// or mysql://`
2711
+ );
2712
+ }
2713
+ try {
2714
+ const connectionConfig = {
2715
+ connectionString: this.config.connectionString,
2716
+ family: 4
2717
+ // Force IPv4 only (disable IPv6)
2718
+ };
2719
+ this.knexInstance = knex({
2720
+ client,
2721
+ connection: connectionConfig,
2722
+ pool: this.config.pool,
2723
+ acquireConnectionTimeout: this.config.acquireConnectionTimeout,
2724
+ ...this.config.ssl && { ssl: this.config.ssl }
2725
+ });
2726
+ if (this.config.profile) {
2727
+ this.attachProfiler();
2728
+ }
2729
+ if (this.config.testConnection) {
2730
+ await this.testConnection();
2731
+ }
2732
+ this.isConnected = true;
2733
+ this.logger.debug?.(`[Db] Connected to database "${this.config.name || this.config.connectionString}"`);
2734
+ } catch (error) {
2735
+ if (error instanceof ParamError) {
2736
+ throw error;
2737
+ }
2738
+ const errorMsg = this.getErrorMessage(error);
2739
+ throw new ParamError(`Db: Connection failed - ${errorMsg}`);
2740
+ }
2741
+ }
2742
+ /**
2743
+ * Disconnect from the database
2744
+ */
2745
+ async disconnect() {
2746
+ if (!this.knexInstance) {
2747
+ return;
2748
+ }
2749
+ try {
2750
+ await this.knexInstance.destroy();
2751
+ this.knexInstance = null;
2752
+ this.isConnected = false;
2753
+ this.queriesLog = [];
2754
+ this.logger.debug?.(`[Db] Disconnected from database "${this.config.name || this.config.connectionString}"`);
2755
+ } catch (error) {
2756
+ const errorMsg = this.getErrorMessage(error);
2757
+ this.logger.error?.(`[Db] Error disconnecting: ${errorMsg}`);
2758
+ throw error;
2759
+ }
2760
+ }
2761
+ /**
2762
+ * Extract error message from various error types
2763
+ */
2764
+ getErrorMessage(error) {
2765
+ if (error instanceof AggregateError) {
2766
+ const errors = error.errors || [];
2767
+ if (errors.length > 0) {
2768
+ const firstError = errors[0];
2769
+ const firstErrorMsg = firstError instanceof Error ? firstError.message : String(firstError);
2770
+ const allSimilar = errors.every((e) => {
2771
+ const msg = e instanceof Error ? e.message : String(e);
2772
+ const codeMatch = msg.match(/^(\w+)\s/);
2773
+ const firstCodeMatch = firstErrorMsg.match(/^(\w+)\s/);
2774
+ return codeMatch && firstCodeMatch && codeMatch[1] === firstCodeMatch[1];
2775
+ });
2776
+ if (allSimilar && errors.length > 1) {
2777
+ const addresses = errors.map((e) => {
2778
+ const msg = e instanceof Error ? e.message : String(e);
2779
+ const addrMatch = msg.match(/([:\d.]+:\d+)/);
2780
+ return addrMatch ? addrMatch[1] : null;
2781
+ }).filter(Boolean);
2782
+ if (addresses.length > 0) {
2783
+ const codeMatch = firstErrorMsg.match(/^(\w+)\s/);
2784
+ const code = codeMatch ? codeMatch[1] : "Connection error";
2785
+ return `${code} (tried: ${addresses.join(", ")})`;
2786
+ }
2787
+ }
2788
+ const uniqueMessages = [...new Set(errors.map((e) => {
2789
+ return e instanceof Error ? e.message : String(e);
2790
+ }))];
2791
+ if (uniqueMessages.length === 1) {
2792
+ return uniqueMessages[0];
2793
+ }
2794
+ return uniqueMessages.join("; ");
2795
+ }
2796
+ return error.message || "Multiple errors occurred";
2797
+ }
2798
+ if (error instanceof Error) {
2799
+ const errorWithCode = error;
2800
+ if (errorWithCode.code) {
2801
+ return `${errorWithCode.code}: ${error.message || String(error)}`;
2802
+ }
2803
+ return error.message || String(error);
2804
+ }
2805
+ if (typeof error === "string") {
2806
+ return error;
2807
+ }
2808
+ if (error?.message) {
2809
+ const msg = String(error.message);
2810
+ const errorWithCode = error;
2811
+ if (errorWithCode.code) {
2812
+ return `${errorWithCode.code}: ${msg}`;
2813
+ }
2814
+ return msg;
2815
+ }
2816
+ return String(error) || "Unknown error";
2817
+ }
2818
+ /**
2819
+ * Test database connection
2820
+ */
2821
+ async testConnection() {
2822
+ if (!this.knexInstance) {
2823
+ throw new Error("Db: Not connected. Call connect() first.");
2824
+ }
2825
+ try {
2826
+ const result = await this.knexInstance.raw("SELECT 2+3 AS result");
2827
+ const isOk = result.rows?.[0]?.result === 5 || result[0]?.[0]?.result === 5;
2828
+ this.logger.debug?.(`[Db] Connection test: ${isOk ? "OK" : "FAILED"}`);
2829
+ return isOk;
2830
+ } catch (error) {
2831
+ const errorMsg = this.getErrorMessage(error);
2832
+ this.logger.error?.(`[Db] Connection test failed: ${errorMsg}`);
2833
+ throw new ParamError(`Db: Connection test failed - ${errorMsg}`);
2834
+ }
2835
+ }
2836
+ /**
2837
+ * Attach query profiler to log all queries
2838
+ */
2839
+ attachProfiler() {
2840
+ if (!this.knexInstance) {
2841
+ return;
2842
+ }
2843
+ this.queriesLog = [];
2844
+ this.knexInstance.queriesLog = this.queriesLog;
2845
+ this.knexInstance.on("query", (query) => {
2846
+ query.__startTime = process.hrtime();
2847
+ });
2848
+ this.knexInstance.on("query-response", (response, query) => {
2849
+ const [seconds, nanoseconds] = process.hrtime(query.__startTime);
2850
+ const executionTimeMs = (seconds * 1e3 + nanoseconds / 1e6).toFixed(2);
2851
+ const logEntry = {
2852
+ sql: query.sql,
2853
+ bindings: query.bindings || [],
2854
+ executionTimeMs
2855
+ };
2856
+ this.queriesLog.push(logEntry);
2857
+ this.logger.debug?.(`[Db] Query: ${query.sql} | Duration: ${executionTimeMs}ms`);
2858
+ });
2859
+ this.knexInstance.on("query-error", (error, query) => {
2860
+ this.logger.error?.(`[Db] Query failed: ${query.sql}`, error);
2861
+ });
2862
+ }
2863
+ /**
2864
+ * Get query log (only available if profiling is enabled)
2865
+ */
2866
+ getQueryLog() {
2867
+ return [...this.queriesLog];
2868
+ }
2869
+ /**
2870
+ * Check if a table exists
2871
+ */
2872
+ async tableExists(tableName) {
2873
+ if (!this.knexInstance) {
2874
+ throw new Error("Db: Not connected. Call connect() first.");
2875
+ }
2876
+ try {
2877
+ return await this.knexInstance.schema.hasTable(tableName);
2878
+ } catch (error) {
2879
+ this.logger.error?.(`[Db] Error checking table existence: ${error.message}`);
2880
+ throw error;
2881
+ }
2882
+ }
2883
+ /**
2884
+ * Get the underlying Knex instance (for advanced usage)
2885
+ */
2886
+ getKnex() {
2887
+ if (!this.knexInstance) {
2888
+ throw new Error("Db: Not connected. Call connect() first.");
2889
+ }
2890
+ return this.knexInstance;
2891
+ }
2892
+ /**
2893
+ * Get connection status
2894
+ */
2895
+ isConnectedToDb() {
2896
+ return this.isConnected && this.knexInstance !== null;
2897
+ }
2898
+ };
2604
2899
  export {
2605
2900
  Args,
2901
+ Db,
2606
2902
  Divider,
2607
2903
  FileDatabase,
2608
2904
  FileDatabaseError,