rake-db 2.4.44 → 2.6.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.d.ts CHANGED
@@ -287,7 +287,7 @@ declare const dropDb: (arg: MaybeArray<AdapterOptions>) => Promise<void>;
287
287
  declare const resetDb: (arg: MaybeArray<AdapterOptions>, config: RakeDbConfig) => Promise<void>;
288
288
 
289
289
  declare const writeMigrationFile: (config: RakeDbConfig, version: string, name: string, content: string) => Promise<void>;
290
- declare const generate: (config: RakeDbConfig, args: string[]) => Promise<void>;
290
+ declare const generate: (config: RakeDbConfig, [name]: string[]) => Promise<void>;
291
291
  declare const makeFileTimeStamp: () => string;
292
292
 
293
293
  type ChangeCallback = (db: Migration, up: boolean) => Promise<void>;
package/dist/index.js CHANGED
@@ -1683,9 +1683,13 @@ const migrateOrRollback = async (options, config, args, up) => {
1683
1683
  }
1684
1684
  };
1685
1685
  const changeCache = {};
1686
+ const begin = {
1687
+ text: "BEGIN",
1688
+ values: orchidCore.emptyArray
1689
+ };
1686
1690
  const processMigration = async (db, up, file, config, options, appCodeUpdaterCache) => {
1687
1691
  var _a;
1688
- const asts = await db.transaction(async (tx) => {
1692
+ const asts = await db.transaction(begin, async (tx) => {
1689
1693
  const db2 = createMigrationInterface(tx, up, config);
1690
1694
  clearChanges();
1691
1695
  let changes = changeCache[file.path];
@@ -1849,17 +1853,11 @@ const writeMigrationFile = async (config, version, name, content) => {
1849
1853
  await promises.writeFile(filePath, content);
1850
1854
  (_a = config.logger) == null ? void 0 : _a.log(`Created ${orchidCore.pathToLog(filePath)}`);
1851
1855
  };
1852
- const generate = async (config, args) => {
1853
- const name = args[0];
1856
+ const generate = async (config, [name]) => {
1854
1857
  if (!name)
1855
1858
  throw new Error("Migration name is missing");
1856
1859
  const version = makeFileTimeStamp();
1857
- await writeMigrationFile(
1858
- config,
1859
- version,
1860
- name,
1861
- makeContent(name, args.slice(1))
1862
- );
1860
+ await writeMigrationFile(config, version, name, makeContent(name));
1863
1861
  };
1864
1862
  const makeFileTimeStamp = () => {
1865
1863
  const now = /* @__PURE__ */ new Date();
@@ -1872,7 +1870,7 @@ const makeFileTimeStamp = () => {
1872
1870
  now.getUTCSeconds()
1873
1871
  ].map((value) => value < 10 ? `0${value}` : value).join("");
1874
1872
  };
1875
- const makeContent = (name, args) => {
1873
+ const makeContent = (name) => {
1876
1874
  let content = `import { change } from 'rake-db';
1877
1875
 
1878
1876
  change(async (db) => {`;
@@ -1880,42 +1878,27 @@ change(async (db) => {`;
1880
1878
  if (rest) {
1881
1879
  if (first === "create" || first === "drop") {
1882
1880
  content += `
1883
- await db.${first === "create" ? "createTable" : "dropTable"}('${rest}', (t) => ({`;
1884
- content += makeColumnsContent(args);
1885
- content += "\n }));";
1881
+ await db.${first === "create" ? "createTable" : "dropTable"}('${rest}', (t) => ({
1882
+
1883
+ }));`;
1886
1884
  } else if (first === "change") {
1887
1885
  content += `
1888
- await db.changeTable('${rest}', (t) => ({`;
1889
- content += "\n }));";
1886
+ await db.changeTable('${rest}', (t) => ({
1887
+
1888
+ }));`;
1890
1889
  } else if (first === "add" || first === "remove") {
1891
1890
  const table = first === "add" ? getTextAfterTo(rest) : getTextAfterFrom(rest);
1892
1891
  content += `
1893
- await db.changeTable(${table ? `'${table}'` : "tableName"}, (t) => ({`;
1894
- content += makeColumnsContent(args, first);
1895
- content += "\n }));";
1892
+ await db.changeTable(${table ? `'${table}'` : "tableName"}, (t) => ({
1893
+
1894
+ }));`;
1896
1895
  }
1897
1896
  }
1898
1897
  return content + "\n});\n";
1899
1898
  };
1900
- const makeColumnsContent = (args, method) => {
1901
- let content = "";
1902
- const prepend = method ? `t.${method}(` : "";
1903
- const append = method ? ")" : "";
1904
- for (const arg of args) {
1905
- const [name, def] = arg.split(":");
1906
- if (!def) {
1907
- throw new Error(
1908
- `Column argument should be similar to name:type, name:type.method1.method2, name:type(arg).method(arg). Example: name:varchar(20).nullable. Received: ${arg}`
1909
- );
1910
- }
1911
- const methods = def.split(".").map((method2) => method2.endsWith(")") ? `.${method2}` : `.${method2}()`);
1912
- content += `
1913
- ${name}: ${prepend}t${methods.join("")}${append},`;
1914
- }
1915
- return content;
1916
- };
1917
1899
 
1918
1900
  const filterSchema = (table) => `${table} !~ '^pg_' AND ${table} != 'information_schema'`;
1901
+ const jsonAgg = (sql2, as) => `(SELECT coalesce(json_agg(t.*), '[]') FROM (${sql2}) t) AS "${as}"`;
1919
1902
  const columnsSql = ({
1920
1903
  schema,
1921
1904
  table,
@@ -1997,50 +1980,33 @@ WHERE a.attnum > 0
1997
1980
  AND NOT a.attisdropped
1998
1981
  AND ${where}
1999
1982
  ORDER BY a.attnum`;
2000
- class DbStructure {
2001
- constructor(db) {
2002
- this.db = db;
2003
- }
2004
- async getSchemas() {
2005
- const { rows } = await this.db.arrays(
2006
- `SELECT n.nspname "name"
1983
+ const schemasSql = `SELECT coalesce(json_agg(nspname ORDER BY nspname), '[]')
2007
1984
  FROM pg_catalog.pg_namespace n
2008
- WHERE ${filterSchema("n.nspname")}
2009
- ORDER BY "name"`
2010
- );
2011
- return rows.flat();
2012
- }
2013
- async getTables() {
2014
- const { rows } = await this.db.query(
2015
- `SELECT
1985
+ WHERE ${filterSchema("nspname")}`;
1986
+ const tablesSql = `SELECT
2016
1987
  nspname AS "schemaName",
2017
1988
  relname AS "name",
2018
1989
  obj_description(c.oid) AS comment,
2019
1990
  (SELECT coalesce(json_agg(t), '[]') FROM (${columnsSql({
2020
- schema: "n",
2021
- table: "c",
2022
- where: "a.attrelid = c.oid"
2023
- })}) t) AS "columns"
1991
+ schema: "n",
1992
+ table: "c",
1993
+ where: "a.attrelid = c.oid"
1994
+ })}) t) AS "columns"
2024
1995
  FROM pg_class c
2025
1996
  JOIN pg_catalog.pg_namespace n ON n.oid = relnamespace
2026
1997
  WHERE relkind = 'r'
2027
1998
  AND ${filterSchema("nspname")}
2028
- ORDER BY relname`
2029
- );
2030
- return rows;
2031
- }
2032
- async getViews() {
2033
- const { rows } = await this.db.query(
2034
- `SELECT
1999
+ ORDER BY relname`;
2000
+ const viewsSql = `SELECT
2035
2001
  nc.nspname AS "schemaName",
2036
2002
  c.relname AS "name",
2037
2003
  right(substring(r.ev_action from ':hasRecursive w'), 1)::bool AS "isRecursive",
2038
2004
  array_to_json(c.reloptions) AS "with",
2039
2005
  (SELECT coalesce(json_agg(t), '[]') FROM (${columnsSql({
2040
- schema: "nc",
2041
- table: "c",
2042
- where: "a.attrelid = c.oid"
2043
- })}) t) AS "columns",
2006
+ schema: "nc",
2007
+ table: "c",
2008
+ where: "a.attrelid = c.oid"
2009
+ })}) t) AS "columns",
2044
2010
  pg_get_viewdef(c.oid) AS "sql"
2045
2011
  FROM pg_namespace nc
2046
2012
  JOIN pg_class c
@@ -2049,38 +2015,20 @@ JOIN pg_class c
2049
2015
  AND c.relpersistence != 't'
2050
2016
  JOIN pg_rewrite r ON r.ev_class = c.oid
2051
2017
  WHERE ${filterSchema("nc.nspname")}
2052
- ORDER BY c.relname`
2053
- );
2054
- return rows;
2018
+ ORDER BY c.relname`;
2019
+ const sql = `SELECT (${schemasSql}) AS "schemas", ${jsonAgg(
2020
+ tablesSql,
2021
+ "tables"
2022
+ )}, ${jsonAgg(viewsSql, "views")}`;
2023
+ class DbStructure {
2024
+ constructor(db) {
2025
+ this.db = db;
2055
2026
  }
2056
- async getProcedures() {
2057
- const { rows } = await this.db.query(
2058
- `SELECT
2059
- n.nspname AS "schemaName",
2060
- proname AS name,
2061
- proretset AS "returnSet",
2062
- (
2063
- SELECT typname FROM pg_type WHERE oid = prorettype
2064
- ) AS "returnType",
2065
- prokind AS "kind",
2066
- coalesce((
2067
- SELECT true FROM information_schema.triggers
2068
- WHERE n.nspname = trigger_schema AND trigger_name = proname
2069
- LIMIT 1
2070
- ), false) AS "isTrigger",
2071
- coalesce((
2072
- SELECT json_agg(pg_type.typname)
2073
- FROM unnest(coalesce(proallargtypes, proargtypes)) typeId
2074
- JOIN pg_type ON pg_type.oid = typeId
2075
- ), '[]') AS "types",
2076
- coalesce(to_json(proallargtypes::int[]), to_json(proargtypes::int[])) AS "argTypes",
2077
- coalesce(to_json(proargmodes), '[]') AS "argModes",
2078
- to_json(proargnames) AS "argNames"
2079
- FROM pg_proc p
2080
- JOIN pg_namespace n ON p.pronamespace = n.oid
2081
- WHERE ${filterSchema("n.nspname")}`
2082
- );
2083
- return rows;
2027
+ async getStructure() {
2028
+ const {
2029
+ rows: [structure]
2030
+ } = await this.db.query(sql);
2031
+ return structure;
2084
2032
  }
2085
2033
  async getIndexes() {
2086
2034
  const { rows } = await this.db.query(
@@ -2490,18 +2438,14 @@ const structureToAst = async (ctx, db) => {
2490
2438
  };
2491
2439
  const getData = async (db) => {
2492
2440
  const [
2493
- schemas,
2494
- tables,
2495
- views,
2441
+ { schemas, tables, views },
2496
2442
  constraints,
2497
2443
  indexes,
2498
2444
  extensions,
2499
2445
  enums,
2500
2446
  domains
2501
2447
  ] = await Promise.all([
2502
- db.getSchemas(),
2503
- db.getTables(),
2504
- db.getViews(),
2448
+ db.getStructure(),
2505
2449
  db.getConstraints(),
2506
2450
  db.getIndexes(),
2507
2451
  db.getExtensions(),
@@ -3102,6 +3046,9 @@ const rakeDb = async (options, partialConfig = {}, args = process.argv.slice(2))
3102
3046
  };
3103
3047
  const help = `Usage: rake-db [command] [arguments]
3104
3048
 
3049
+ See documentation at:
3050
+ https://orchid-orm.netlify.app/guide/migration-commands.html
3051
+
3105
3052
  Commands:
3106
3053
  create create databases
3107
3054
  drop drop databases
@@ -3124,17 +3071,6 @@ Rollback arguments:
3124
3071
  Migrate and rollback common arguments:
3125
3072
  --code run code updater, overrides \`useCodeUpdater\` option
3126
3073
  --code false do not run code updater
3127
-
3128
- New migration file arguments:
3129
- - (required) first argument is migration name
3130
- * create* template for create table
3131
- * change* template for change table
3132
- * add*To* template for add columns
3133
- * remove*From* template for remove columns
3134
- * drop* template for drop table
3135
-
3136
- - other arguments considered as columns with types and optional methods:
3137
- rake-db new createTable id:serial.primaryKey name:text.nullable
3138
3074
  `;
3139
3075
 
3140
3076
  exports.MigrationBase = MigrationBase;