rahmanfadhil / cotton Goto Github PK
View Code? Open in Web Editor NEWSQL Database Toolkit for Deno
Home Page: https://rahmanfadhil.github.io/cotton
License: MIT License
SQL Database Toolkit for Deno
Home Page: https://rahmanfadhil.github.io/cotton
License: MIT License
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
It would be great to have a syntax like sequelize model create that sets the fields and then add the row to the database.
Are you planning to add more features like hooks?
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.
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()
?
Trying to follow the instructions in the docs to install the CLI tool, so I can run migrations using Cotton.
deno install --allow-net --allow-read --allow-write -n cotton https://deno.land/x/[email protected]/cli.ts
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)
Could use a Microsoft SQL Server adapter!? 🤷🏾♂️
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
It's too bad that this could not be just 'added' as feature without recompiling everything :/
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.
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();
cotton migration:up
=> not OK, CLI will not exit !Same for migration:info, etc, CLI will not exit !
Does Cotton support creating or executing prepared statements?
If not, is that something you are considering adding?
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.
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;
}
}
Is anyone working on adding left join to query builder? If not I would like to take a shot at it.
Hi, can we translate the homepage into Chinese
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!
Hi, I really want to use this in my project but so far it looks unmaintained. Is this the case or...?
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
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 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.
Coba execute query SELECT CURRENT_DATABASE()
. pakai postgre, nanti dia keluar error kaya diatas.
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
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
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.
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?
Any plans on expanding to MongoDB support?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.