Giter VIP home page Giter VIP logo

cotton's People

Contributors

atsjj avatar borisliu avatar cvng avatar franklinharvey avatar guzhongren avatar leonardo-rocha avatar rahmanfadhil avatar sayore avatar u-ways avatar zfi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

cotton's Issues

error: impossible install

Hi
in version:
deno 1.4.6
v8 8.7.220.3
typescript 4.0.3

if try to install cotton cli:

Warning std versions prefixed with 'v' were deprecated recently. Please change your import to https://deno.land/[email protected]/fmt/colors.ts (at https://deno.land/[email protected]/fmt/colors.ts)
error: Import 'https://deno.land/[email protected]/fmt/colors.ts' failed: 404 Not Found
Imported from "https://deno.land/x/[email protected]/deps.ts:12".

You can solve resolve this problem?
thanks

Suggestions

Suggestion

It would be great to have a syntax like sequelize model create that sets the fields and then add the row to the database.

Question

Are you planning to add more features like hooks?

Possible contribution

Also, I just made a method that erases the rows (with TRUNCATE) of all the tables created by models. As it's just a method I didn't bother to open a pull request and maybe there's a better approach to it like saving all created tables in the database object and obviously this command is different depending on the database. I also had to search on the folder because there may be other tables that were not created using the model, like nessie-migrations table.


import { walk } from 'https://deno.land/std/fs/mod.ts';
import db from '../../src/database/db.ts';

const modelsDir = './src/app/models';
const matchFilter: RegExp[] = [];
matchFilter.push(new RegExp('[:upper:]*[a-z].ts'));

/**
 * Clear all model tables from the database.
 * Uses the statement 'TRUNCATE <tablename>'
 */
export default async function truncateModels() {
  for await (const entry of walk(modelsDir, { match: matchFilter })) {
    const pathSplit = entry.path.split('/');
    const model = pathSplit[3].toLowerCase();
    const tableName = model.split('.')[0] + 's';
    await db.execute(`TRUNCATE ${tableName};`);
  }
}

Finally, thanks for the module! it's working great.

@Column requires type

The docs for models say "Cotton is smart enough to determine the data type of that particular column using TypeScript types. However, you can still customize your column types by passing the type option like below." Then it shows this:

@Column({ type: DataType.String })
email!: string;

When I try this:

  @Column()
  name!: string;

without passing a type to @Column I get the error "Column '${propertyKey}' must have a type!".
If I do pass the type to @Column then it works.
Should I really be able to just use @Column()?

Can't install the CLI using the command in the docs

Trying to follow the instructions in the docs to install the CLI tool, so I can run migrations using Cotton.

The command

deno install --allow-net --allow-read --allow-write -n cotton https://deno.land/x/[email protected]/cli.ts

Output

error: Uncaught SyntaxError: The requested module './levels.ts' does not provide an export named 'LevelName'
export { LogLevels, LevelName } from "./levels.ts";
                    ^
    at <anonymous> (https://deno.land/[email protected]/log/mod.ts:13:21)

Mssql support?

Could use a Microsoft SQL Server adapter!? 🤷🏾‍♂️

Feature: JSON Fields

I would love to see JSON fields supported by cotton. Not including the full syntax but at least the handling of the data itself.

As far as I saw almost all that would left to do seems to

  • add a json type
  • update bindvalues in order to understand that Objects could be posted as strings
  • decode after fetching the values

It's too bad that this could not be just 'added' as feature without recompiling everything :/

how to delete all rows from a table

I tried this:

await db.table("dogs").delete().execute();

but that gives the error "Cannot perform delete without any constraints!".

Is there a way to do this? I also tried this:

await db.table("dogs").delete().where('name', '*').execute();

It seems that wildcards are not supported.

Allow Object type in queries when using Postgres

Postgres has support for JSON data via the json and jsonb datatypes, but Cotton's DatabaseValues doesn't include Object so queries like below result in a Typescript error even though they are correct.

db
  .table("test")
  .insert({
    "user_id": userId,
    data: {
      // @ts-ignore Have to add a ts-ignore here to get this to run
      "json_key": "some value",
      "another_key": 1,
      "is_key": true
    }
  })
.execute();

CLI will not always exit

  1. installing cotton CLI (to play with migrations) => OK
  2. creating a migration file => OK
  3. running cotton migration:up => not OK, CLI will not exit !

Same for migration:info, etc, CLI will not exit !

prepared statements

Does Cotton support creating or executing prepared statements?
If not, is that something you are considering adding?

Maybe typo in cli.ts with migration:down command?

Hi guys, thanks for this nice library, loved it.

I think this probably there is a typo at cli.ts:156 it should be migration:down instead of migrations:down ?

Running cotton migration:down as pointed in docs shows this error message and looks like is related to that.

Screen Shot 2020-10-11 at 00 25 09

[BUG] ORM Returning `null` for random fields

Running the following query:

const user = await this.db
  .getManager()
  .query(User)
  .where('email', email)
  .first();

Returns the following object:

User {
  id: 3,
  codename: "SomeCodename",
  email: "[email protected]",
  password: "$2a$08$ckrMPfkyeT0Lat2Ajadd0OtnUBxi0ryHpWlxOqHNGb8I8.gAVKULK",
  age: 24,
  createdAt: 2021-01-19T01:02:02.000Z,    
  updatedAt: 2021-01-19T01:02:02.000Z,    
  parentEmail: null,
  roleId: null,
  isValidated: null
}

In PGAdmin, the parentEmail, roleId, and isValidated fields are all set. Unsure why this is happening, as updating the fields through the ORM seems to be working correctly? For instance, I'm able to sign a user up with ORM and show all fields correct in PGAdmin, then I'm able to update validation status correctly. When I run this query though, those 3 fields are always null.

I'm using the latest release of Cotton (0.7.5) and running Deno v1.6.3.

For reference, the User model looks like this:

@Model('users')
export default class User {
  @Primary()
  id!: number;

  @Column({ type: DataType.String })
  codename!: string;

  @Column({ type: DataType.String })
  email!: string;

  @Column({ type: DataType.String })
  parentEmail!: string;

  @Column({ type: DataType.String })
  password!: string;

  @Column({ type: DataType.Number })
  age!: number;

  @Column({ type: DataType.Number })
  roleId!: number;

  @Column({ type: DataType.Boolean })
  isValidated!: boolean;

  @Column({ type: DataType.Date, default: () => new Date().toUTCString() })
  createdAt!: Date;

  @Column({ type: DataType.Date, default: () => new Date().toUTCString() })
  updatedAt!: Date;

  @BelongsTo(() => Role, 'roleId')
  role!: Role;

  @HasMany(() => User, 'userId')
  validations!: Validation[];

  public generateFrom(body: INewUser) {
    this.age = body.age;
    this.codename = body.codename;
    this.email = body.email;
    this.parentEmail = body.parentEmail;
    this.password = body.password;
    this.roleId = body.roleId;
  }
}

Query Builder: Left Join

Is anyone working on adding left join to query builder? If not I would like to take a shot at it.

[BUGFIX] Upgrade Deno package to reflect Postgres changes

Postgres was recently updated to fix the following bug:

error: TS2345 [ERROR]: Argument of type 'T | undefined' is not assignable to parameter of type 'T | PromiseLike<T>'.
  Type 'undefined' is not assignable to type 'T | PromiseLike<T>'.      resolve(value);
              ~~~~~
    at https://deno.land/x/[email protected]/utils.ts:94:15

Simply upgrading the package from pg v0.4.5 to v0.4.6 should fix the issue, as it has with a few other packages :)

I'm very excited to use your library as it seems fairly robust and awesome <3 Thanks for your time!

is this unmaintained/dead?

Hi, I really want to use this in my project but so far it looks unmaintained. Is this the case or...?

Support schemas in query builder

I might be missing something, but I don't see any examples of using the query builder to run a query in a specific schema. Looking through the code, I don't see any functions on the query builder to add a schema prefix either. I tried the snippet below to query my database:

const users = await db.table("app.user").where("id", 1).execute();
console.log(users);

But it fails with a PostgresError: relation "app.user" does not exist

Models question

Is there any possible way to create table based of a model, I think I can create a schema that follow the model, but that also means I have to maintain the both the schema create table AND the model types, which isn't the end of the world for maybe having a 1 - 3 models but once you get a decent number of models, I think it could be quite tedious to maintain both.

If it is possible to create a table from its model, that would be great to hear and also if any of this does not make sense, feel free to ask for more clarfication

schema create table for null ?

schema columns is null and primary
another like this
await schema.createTable("test", (table) => { table.custom("test_id integer NOT NULL,PRIMARY KEY (test_id)"); });
can i do like this
table.varchar("names", 50,isnull or is not null);
thank you for best library.

deleting a row

i can only delete a row when i use execute() method after delete(), but in guide/query-builder.html#delete

The only thing you need to do to perform DELETE query is by adding delete method to the query builder.

don't mention that.

it is normal or am i forgotten something?

sorry for my bad english

Novato con dudas

Hay forma de usar los decoradores de lo que es Model y BaseModel sin usar typescript ya que cuando uso javascript le lanza un error al ejecutar deno que dice "se esperaba token" en la línea donde se usa el decorador aun que agregó allowjs:true en tsconfig.json

Feature: Migrations

Just like replace is doing it for Data, we could add an utility function which looks at first if a table exists, if not create it, and if the table exists also checks if fields|columns are missing, adds them in a non-destructive fashion.

I've already made an Table Creator that i could PR(if wanted)

Ex.:

checkTableExists('session').then(...).catch(() => {
           createTable("session", [
                new BaseField('id').isUnique().setType("VARCHAR(256)"),
                new BaseField('created_at').setType('BIGNUMBER')
            ])
        })

It doesn't yet support checking for fields missing. Though creating a table would be a useful addition i think.

Stored Procedures and Function

I did not saw it in the documentation so I am not sure this is already in place.
How would you execute a stored procedure or function?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.