Skip to content

Commit

Permalink
Merge pull request #43 from halvardssm/qb/fix-updated-at
Browse files Browse the repository at this point in the history
Changed schema to use array instead of string for queries
  • Loading branch information
halvardssm authored Jun 2, 2020
2 parents 8b00fc1 + d9298e2 commit 060871d
Show file tree
Hide file tree
Showing 19 changed files with 142 additions and 111 deletions.
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,23 +88,26 @@ export default config;
Minimal example of a migration file

```ts
export const up = (): string => {
import { Migration } from "https://deno.land/x/nessie/mod.ts";

export const up: Migration = () => {
return "CREATE TABLE table1 (id int);";
};

export const down = (): string => {
export const down: Migration = () => {
return "DROP TABLE table1";
};
```

Using the native query builder

```ts
import { Migration } from "https://deno.land/x/nessie/mod.ts";
import { Schema, dbDialects } from "https://deno.land/x/nessie/qb.ts";

const dialect: dbDialects = "mysql"

export const up = (): string => {
export const up: Migration = () => {
let query = new Schema(dialect).create("users", (table) => {
table.id();
table.string("name", 100).nullable();
Expand All @@ -120,7 +123,7 @@ export const up = (): string => {
return query
};

export const down = (): void => {
export const down: Migration = () => {
return new Schema(dialect).drop("users");
};
```
Expand Down
6 changes: 3 additions & 3 deletions cli/templates/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ClientPostgreSQL } from "../../clients/ClientPostgreSQL.ts";
import { ClientMySQL } from "../../clients/ClientMySQL.ts";
import { ClientSQLite } from "../../clients/ClientSQLite.ts";
import { ClientPostgreSQL } from "https://deno.land/x/nessie/mod.ts";
import { ClientMySQL } from "https://deno.land/x/nessie/mod.ts";
import { ClientSQLite } from "https://deno.land/x/nessie/mod.ts";

const migrationFolder = "./migrations";

Expand Down
7 changes: 4 additions & 3 deletions cli/templates/migration.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Schema } from "https://deno.land/x/nessie/mod.ts";
import { Migration } from "https://deno.land/x/nessie/mod.ts";
import { Schema } from "https://deno.land/x/nessie/qb.ts";
import Dex from "https://deno.land/x/dex/mod.ts";

export const up = (): string => {
export const up: Migration = () => {
// return new Schema()
// return Dex
};

export const down = (): string => {
export const down: Migration = () => {
};
38 changes: 24 additions & 14 deletions clients/AbstractClient.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import { parsePath } from "../cli/utils.ts";
import { resolve } from "../deps.ts";
import { loggerFn } from "../cli/state.ts";
import { Migration } from "../types.ts";

export type QueryWithString = (string: string) => string;

export type amountRollbackT = number | undefined | "all";
export type amountMigrateT = number | undefined;
export type amountRollbackT = amountMigrateT | "all";
export type queryT = string | string[];
export type QueryHandler = (query: queryT) => Promise<any>;
export type MigrationFile = {
up: Migration;
down: Migration;
};

export interface ClientI {
migrationFolder: string;
prepare: () => Promise<void>;
close: () => Promise<void>;
migrate: (amount: amountMigrateT) => Promise<void>;
rollback: (amount: amountRollbackT) => Promise<void>;
query: (query: queryT) => Promise<any>;
query: QueryHandler;
setLogger: loggerFn;
}

Expand Down Expand Up @@ -52,7 +58,7 @@ export class AbstractClient {
protected async migrate(
amount: amountMigrateT,
latestMigration: string | undefined,
queryHandler: (query: string) => Promise<any>,
queryHandler: QueryHandler,
) {
this.logger(amount, "Amount pre");

Expand All @@ -71,14 +77,16 @@ export class AbstractClient {

for (let i = 0; i < amount; i++) {
const file = this.migrationFiles[i];
let { up } = await import(parsePath(this.migrationFolder, file.name));
let { up }: MigrationFile = await import(
parsePath(this.migrationFolder, file.name)
);

let query: string = await up();
let query = await up();

if (!query || typeof query !== "string") query = "";
if (!query.endsWith(";")) query += ";";
if (!query) query = [];
else if (typeof query === "string") query = [query];

query += this.QUERY_MIGRATION_INSERT(file.name);
query.push(this.QUERY_MIGRATION_INSERT(file.name));

await queryHandler(query);

Expand All @@ -103,7 +111,7 @@ export class AbstractClient {
async rollback(
amount: amountRollbackT,
allMigrations: string[] | undefined,
queryHandler: (query: string) => Promise<any>,
queryHandler: QueryHandler,
) {
this.logger(amount, "Amount pre");

Expand All @@ -120,14 +128,16 @@ export class AbstractClient {

for (let i = 0; i < amount; i++) {
const fileName = allMigrations[i];
let { down } = await import(parsePath(this.migrationFolder, fileName));
let { down }: MigrationFile = await import(
parsePath(this.migrationFolder, fileName)
);

let query: string = await down();
let query = await down();

if (!query || typeof query !== "string") query = "";
if (!query.endsWith(";")) query += ";";
if (!query) query = [];
else if (typeof query === "string") query = [query];

query += this.QUERY_MIGRATION_DELETE(fileName);
query.push(this.QUERY_MIGRATION_DELETE(fileName));

await queryHandler(query);

Expand Down
15 changes: 9 additions & 6 deletions examples/migration-basic.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import { Schema } from "https://deno.land/x/nessie/mod.ts";
import { Migration } from "https://deno.land/x/nessie/mod.ts";
import { Schema } from "https://deno.land/x/nessie/qb.ts";

export const up = (): string => {
const sql1 = new Schema("pg").create("basic", (table) => {
export const up: Migration = () => {
const schema = new Schema("pg");

schema.create("basic", (table) => {
table.id();
table.string("name", 100).nullable();
table.boolean("is_true").default("false");
table.custom("custom_column int default 1");
table.timestamps();
});

const sql2 = new Schema("pg").queryString(
schema.queryString(
"INSERT INTO users VALUES (DEFAULT, 'Deno', true, 2, DEFAULT, DEFAULT);",
);

return sql1 + sql2;
return schema.query;
};

export const down = (): string => {
export const down: Migration = () => {
return new Schema("pg").drop("basic");
};
7 changes: 4 additions & 3 deletions examples/migration-column-config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Schema } from "https://deno.land/x/nessie/mod.ts";
import { Migration } from "https://deno.land/x/nessie/mod.ts";
import { Schema } from "https://deno.land/x/nessie/qb.ts";

export const up = () => {
export const up: Migration = () => {
return new Schema().create("column_config", (table) => {
table.string("name", 100).nullable().default("Deno");
table.integer("number").default("0").autoIncrement();
table.boolean("true").custom("default true");
});
};

export const down = () => {
export const down: Migration = () => {
return new Schema().drop("column_config");
};
5 changes: 3 additions & 2 deletions examples/migration-third-party.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Migration } from "https://deno.land/x/nessie/mod.ts";
import Dex from "https://deno.land/x/dex/mod.ts";

export const up = () => {
export const up: Migration = () => {
return Dex({ client: "mysql" }).schema.createTable("test", (table: any) => {
table.bigIncrements("id").primary();
table.string("file_name", 100).unique();
table.timestamps(undefined, true);
});
};

export const down = () => {
export const down: Migration = () => {
return Dex({ client: "mysql" }).schema.dropTable("test");
};
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from "./clients/AbstractClient.ts";
export * from "./clients/ClientMySQL.ts";
export * from "./clients/ClientPostgreSQL.ts";
export * from "./clients/ClientSQLite.ts";
export * from "./types.ts";
60 changes: 22 additions & 38 deletions query-builder/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { dbDialects } from "./TypeUtils.ts";
* By using this exposed class, you can generate sql strings via the helper methods`.
*/
export class Schema {
query: string = "";
query: string[] = [];
dialect: dbDialects;

constructor(dialenct: dbDialects = "pg") {
Expand All @@ -17,34 +17,36 @@ export class Schema {
create(
name: string,
createfn: (table: Table) => void,
): string {
): string[] {
const table = new Table(name, this.dialect);

createfn(table);

const sql = table.toSql();

this.query += sql;
const sqlArray = this._queryHandler(sql);

return sql;
this.query.push(...sqlArray);

return this.query;
}

/** Adds a custom query string to the migration */
queryString(queryString: string): string {
queryString(queryString: string): string[] {
const lastChar = queryString[queryString.length - 1];
if (lastChar != ";") {
queryString += ";";
}
this.query += queryString;
return queryString;
this.query.push(queryString);
return this.query;
}

/** Drops a table */
drop(
name: string | string[],
ifExists: boolean = false,
cascade: boolean = false,
) {
): string[] {
if (typeof name === "string") name = [name];

const sql = `DROP TABLE${ifExists ? " IF EXISTS" : ""} ${
Expand All @@ -53,13 +55,13 @@ export class Schema {
)
}${cascade ? " CASCADE" : ""};`;

this.query += sql;
this.query.push(sql);

return sql;
return this.query;
}

/** Generates a string for checking if a table exists */
hasTable(name: string) {
hasTable(name: string): string {
switch (this.dialect) {
case "mysql":
//SELECT 1 FROM testtable LIMIT 1;
Expand All @@ -71,33 +73,15 @@ export class Schema {
return `SELECT to_regclass('${name}');`;
}
}
}

// export const queryHandler = async (
// queryString: string,
// state: State,
// queryfn: (query: string) => any,
// ) => {
// const queries = queryString.trim().split(/(?<!\\);/);
//
// if (queries[queries.length - 1]?.trim() === "") queries.pop();
//
// state.debug(queries, "Queries");
//
// const results = [];
//
// for (let query of queries) {
// query = query.trim().replace("\\;", ";");
// state.debug(query, "Query");
//
// const result = await queryfn(query + ";");
//
// results.push(result);
// }
//
// state.debug(results, "Query result");
//
// return results;
// };
/** TODO(halvardssm) This is a temporary fix which will have to be sorted out before v1.0 */
private _queryHandler(queryString: string): string[] {
let queries = queryString.trim().split(/(?<!\\);/);
queries = queries
.filter((el) => el.trim() !== "" && el.trim() !== undefined)
.map((el) => `${el.trim().replace(/\\;/g, ";")};`);
return queries;
}
}

export default Schema;
6 changes: 4 additions & 2 deletions tests/cli/1587937822648-test1.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
export const up = (): string => {
import { Migration } from "../../mod.ts";

export const up: Migration = () => {
return "CREATE TABLE testTable1 (id int);";
};

export const down = (): string => {
export const down: Migration = () => {
return "DROP TABLE testTable1";
};
6 changes: 4 additions & 2 deletions tests/cli/1587937822649-test2.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
export const up = (): string => {
import { Migration } from "../../mod.ts";

export const up: Migration = () => {
return "CREATE TABLE testTable2 (id int);";
};

export const down = (): string => {
export const down: Migration = () => {
return "DROP TABLE testTable2";
};
6 changes: 4 additions & 2 deletions tests/cli/1587937822650-test3.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
export const up = (): string => {
import { Migration } from "../../mod.ts";

export const up: Migration = () => {
return "CREATE TABLE testTable3 (id int);";
};

export const down = (): string => {
export const down: Migration = () => {
return "DROP TABLE testTable3";
};
7 changes: 4 additions & 3 deletions tests/query-builder-migrations/1587937822648-basics.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { Migration } from "../../mod.ts";
import { dbDialects, Schema } from "../../qb.ts";

const dialect = Deno.env.get("DB_DIALECT") as dbDialects;

export const up = (): string => {
export const up: Migration = () => {
return new Schema(dialect).create("basics", (table) => {
table.id();
table.string("col_1", 10);
// table.timestamps(); TODO FIX TIMESTAMPS
table.timestamps();
table.enum("col_11", ["enum_1", "enum_2"]);
});
};

export const down = (): string => {
export const down: Migration = () => {
return new Schema(dialect).drop("basics");
};
Loading

0 comments on commit 060871d

Please sign in to comment.