You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I really want to use this library, but i can't know how work with it. I trying to do a d.ts file to improve it use but i need some help to know what do with each method and what it receive as parameters. if somebody can help me, i'll really apreciate it.
Personally, I see greatest benefit when types guide usage of column fields on table object. Ones columns are something that may change often, and we do want computer's help in refactoring via type-checking.
Setting a goal
With this in mind, the following question comes surfaces: How table definition can produce table with the type that has custom columns on it?
What definition will allow for group_id and user_id to be attached to table type as Column type?
Hack
Adapting @spion mentioned d.ts, full text will follow below, if group_id and user_id are treated as Column types, we may use typescipt's &-ing of types like so
Column extends interface for ColumnDefinition, to allow this cast.
It works nicely, in that t.group_id has a correct type, in accordance to what node-sql does!
Analysis
Stepping back, yes, this hack works for the purpose of strictly following columns, attached to table object. Yet, requirement of explicit cast seems ugly, initially.
There are two types of complexity, intrinsic and superficial. An explicit cast to Column serves a secondary purpose of taking a js type for column content. Map of db and js types is many to one, at best, making it an intrinsic complexity.
Then we may ride with extra type information, passing T in Column, so that further things like equals() or gt(), defined for different T related to this, may restrict their inputs, partially limiting amount of feet-shooting.
Asking:
do you like this?
can this be improved?
please, adjust/add function, methods/fields in adapted from anydb-sql, as I am lost in all of these types, like @InDIOS
how far methods on columns, carrier of T, can improve strictness of equals() or gt()
Another alternative is to add sql.intColumn, sql.stringColumn etc functions that automatically assign the type to the column. That would look like this
@spion yes! this works. I still cannot completely grasp types' reshuffling you have in the code (line 28 and 221, taken together ?).
Let's build on it!
Explicit approach makes one write things twice, and name has to go into <>'s, while there also need to be an overarching schema, as well.
What about having a mandatory type filed, not connected with defaultValue, as, I assume, defaultValue has impact on table in db, and we just want to fix js types.
Third example with sql.intColumn() and likes, does it require explicit patching sql? I hesitate, patching modules of others on the fly, unless docs explicitly tell what is allowed in bold.
@3n-mb most of the "magic" is on line 21. For each field name in the type of the table row, create a column type based on the type of that field in the table row.
Now the reason why it wont work without a default value is because TypeScript has to somehow infer what kind of type is the field - once it does that, it can "pull it in" from TableDefinition<Name, Row> up to the table Row type and then use it to generate the Table<Name, Row> columns. If a default value is not provided, the type of Row[CName] remains a mystery to typescript and the entire row must be provided explicitly as a type parameter between <>.
I don't know if its possible to put a type as a field value in the column definition. It might be, with more mapped types hackery, but I don't think it is... Lets try:
typeConstructor<T>={new(t:any):T}
We added a constructor type, now we can add another optional field in the definition that node-sql will never look at:
Its not important what the function returns, its only there to placate TypeScript into accepting the type of the column.
Yes, sql.intColumn and other types of columns would have to be added to node-sql. We could perhaps send a PR for it and if @brianc is okay with it he could merge it. They're just small things that would make it easier and more ergonomic to model the library with typescript... I mean the above hacks work too, they are just annoying and error prone (what if we use dataType int with jsType string? Chaos!)
has is from anydb-sql, it was sort of a failed experiment to model relationships. Feel free to ignore it 😀
One of these days, I'm hoping I'll have the chance to clean all this up and contribute proper typings... but right now I can't
@spion thank you for this piece, it really is useful in the second form, i.e. I am now using it this way, love it so far, in comparison to other ... non-options, in comparison.
I posted code in its entirely, so that other folks may copy and use it directly, buying us time.
For the future, I think that in column interface, things like equals should be using T that is already with the column. You have all of ground work done. At least it seems so.
@3n-mb sorry I started editing my original comment and came up with another hack that almost gets the definitions where you wanted them to be (the only caveat is you need to put the JSONObject function somewhere - probably not in the sql module but something like sql-tools maybe - and import it to create new object types)
edit: actually individual types can be in a separate module called sql-types or something like that. They would generate column definitions with the appropriate dataType for your database... and include all the type goodies that let TS infer what the column contains.
I'm really excited to polish this up a little more... as soon as I find the chance!
before we jump toQuery(), we need to arrest type of this Query<T>. @spion did magic here, and query's generic type will be in this example something along the lines T = { user_id: string } & { params: object|undefined }. So, to extract it, we add a phantom field to interface Query<T>:
Note that I have introduced record's type in the very front, and seeded with its type into sql.define<...>(). Initially, I thought this way is too typing-consuming, but now, after use, I realize that this is the the more lazy way of writing, cause (a) sooner or later you will want to have record type, (b) typing inside define is Ctrl+Space driven activity, (c) any renaming will take all correct places anyway, and (d) reading explicit js type for whole record is easier.
It works for me, so far. @spion do you think there may be other unforeseen things here? Or can this be done better?
selectDeep question
@spion is Queryable.selectDeep(...) from node-sql, or from anydb-sql ?
I am slowly groking this. I can see have name-as-type in a column helps, for example to get query result (previous comment). Table's name is used in selectDeep. Is it used elsewhere? Or do you have another plan for it?
Definitions, round three, adding some more node-sql's own things
regarding select(column1, column2) it should simply work and generate correct new row types without any extra work. It just needs to be removed from the definition of Table as its a duplicate (just select<U>(...nodes:any[]):Query<U>, the other overload that has no arguments is fine). It should be correctly provided already by Queryable<T>.
The same corrections need to be done for SubQuery<T>.
Another thing, Queryable<T> only has overloads up to 3 columns, might be a good idea to add support for bigger select statements (9 columns ought to be enough for everyone?)
selectDeep is added by anydb-sql and it lets you select multiple tables from a join query. It can be safely left out.
@spion have you added Name parameter to type Table to have deepSelect?
Without selectDeep, I tried to remove Name parameter. It simplifies things a bit, but clear naming of type in editor is gone, and editor's help becomes less informative. So, even though, Table's name type isn't used like Column's name, we better keep it for decoration of code-reading activity.
I have been using a few helpers to generate definitions, take a look
here: https://github.com/zenlor/node-sql-types it is probably what you
are looking for, but it hides implementation details under another
layer increasing overall complexity.
It's not complete and it's very opinionated given my use case.
The best integration I could try is still `anydb-sql` but it's in need
of an update on both `node-sql` and the definitions.
I have been thinkering lately with a logicless model implementation but
typescript's type inference, sometimes, is far too strict and difficult
to implement without macros (it would be so much easier with reader
macros)
Still not solved? Oh my. What if want to generate an insert query for some generic table. How do I safely type that, when I do not even know what the types of those tables are?
Still not solved? Oh my. What if want to generate an insert query for some generic table. How do I safely type that, when I do not even know what the types of those tables are?
I use existing typing, and I use it constantly to ensure strict setups of db's. Typing really helps. Start with definition of table, and everything else is checked automagically.
Are you ask about task not being closed. Do you have an impression that there is no typing?
@jayarjo can you flesh it this out a bit more in code snippets of how you want to see things.
This sounds to me like an exercise in flexibility of TypeScript typing mechanism. Do you just put any, or figure it with typeof and other tricks.
@3n-mb I need to be able to generate an sql for insert (or any other type) query out of totally generic tableName and array of column names. Something like:
@jayarjo Have you tried the following partial release of type strictness, assuming also that tableName and columns are not known at time of ts' compilation:
Note that type constraint on table name value is simply enforcing strictness (it saved me once already 😄 ). But putting 'any-name' in type does nothing, cause TypeScript's types exist only when you write code, and not when code (js) runs.
@jayarjo give more context. How is table consumed/used? What doesn't work precisely?
If you have any sensitive elements in code, just strip/replace them, and show context in which you want to use this. Also, what is you typescript version?
@jayarjo I look at types not as a hassle, but as a fun exercise of using very flexible Typescript type system.
Now, I will try to narrow your statement about "too much hassle", as to in your particular case.
In my org you can't commit a db code that is not also vetted in some form by compiler on top of regular reviews -- data security, correctness, etc. Hence, I am interested in cases that require deviation from 100% type strictness.
Can I ask you again, @jayarjo to provide more code. We have spent time to consider your questions. Can you extend the same kindness back to us? Thank you in advance.
@3n-mb I cannot provide my code, sorry. But what I basically did is that I wrote a generic data seeder using pg-structure and faker that generates arbitrary amount of fake seed data, taking into account structure of the given database, types of the columns, format, length, etc. It is actually interesting if there's anything you can recommend for such use case?
@3n-mb I cannot provide my code, sorry. But what I basically did is that I wrote a generic data seeder using pg-structure and faker that generates arbitrary amount of fake seed data, taking into account structure of the given database, types of the columns, format, length, etc. It is actually interesting if there's anything you can recommend for such use case?
You ask for something without providing details. Useful answers can't appear if details are not given. Software craft- men and women take deep personal responsibility and pride in providing useful answers to peer developers.
No one asked for your production code. I asked for code snippets that convey your requirements in more precise language -- computer code. I even reminded you to strip/replace parts that relate to your stuff but are not material to an articulation of problem you've had. My ask still stands.
Do you realize that you've managed to spell "FU" with "sorry"? I am not an emotionless AI, and I stand by my humanity.
@3n-mb no man, you over complicate. And apparently not only in tech. I described my case in quite a detail. Not sure what to add. I doubt that implementation will help to add any context.
Activity
zenlor commentedon Mar 1, 2017
If you want to use it without type checking you can simply:
At least the compiler will not complain about it.
spion commentedon Mar 1, 2017
With the newest mapped types in TypeScript, its actually possible to model node-sql
There is a work-in-progress implementation here: https://github.com/doxout/anydb-sql/blob/4e4c0ff4a7f2efb7f820baaafea1f624f1ae0399/d.ts/anydb-sql.d.ts which can be used as a starting point.
3n-mb commentedon Apr 27, 2017
Personally, I see greatest benefit when types guide usage of column fields on table object. Ones columns are something that may change often, and we do want computer's help in refactoring via type-checking.
Setting a goal
With this in mind, the following question comes surfaces: How table definition can produce table with the type that has custom columns on it?
Let's take table:
What definition will allow for
group_idanduser_idto be attached to table type asColumntype?Hack
Adapting @spion mentioned d.ts, full text will follow below, if
group_idanduser_idare treated asColumntypes, we may use typescipt's&-ing of types like sowith related definition
Note that columns become type loose, which should be explicitly tightened at definition of the table. Let's see how definition should look now:
Columnextends interface forColumnDefinition, to allow this cast.It works nicely, in that
t.group_idhas a correct type, in accordance to what node-sql does!Analysis
Stepping back, yes, this hack works for the purpose of strictly following columns, attached to table object. Yet, requirement of explicit cast seems ugly, initially.
There are two types of complexity, intrinsic and superficial. An explicit cast to
Columnserves a secondary purpose of taking a js type for column content. Map of db and js types is many to one, at best, making it an intrinsic complexity.Then we may ride with extra type information, passing
TinColumn, so that further things likeequals()orgt(), defined for differentTrelated tothis, may restrict their inputs, partially limiting amount of feet-shooting.Asking:
T, can improve strictness ofequals()orgt()Hacked definitions, first round:
spion commentedon Apr 27, 2017
@3n-mb if you provide a defaultValue for the column definition, everything works, e.g. try
If you can't do that, you can provide a type parameter manually:
Another alternative is to add sql.intColumn, sql.stringColumn etc functions that automatically assign the type to the column. That would look like this
and the column types will be correct.
3n-mb commentedon Apr 27, 2017
@spion yes! this works. I still cannot completely grasp types' reshuffling you have in the code (line 28 and 221, taken together ?).
Let's build on it!
Explicit approach makes one write things twice, and name has to go into
<>'s, while there also need to be an overarching schema, as well.What about having a mandatory type filed, not connected with
defaultValue, as, I assume,defaultValuehas impact on table in db, and we just want to fix js types.And example becomes
Third example with
sql.intColumn()and likes, does it require explicit patching sql? I hesitate, patching modules of others on the fly, unless docs explicitly tell what is allowed in bold.Hacked code with jsType, second round:
3n-mb commentedon Apr 27, 2017
@spion is
hasininterface TableDefinitionanydb-sql's construct, or, is it node-sql?spion commentedon Apr 28, 2017
@3n-mb most of the "magic" is on line 21. For each field name in the type of the table row, create a column type based on the type of that field in the table row.
Now the reason why it wont work without a default value is because TypeScript has to somehow infer what kind of type is the field - once it does that, it can "pull it in" from
TableDefinition<Name, Row>up to the tableRowtype and then use it to generate theTable<Name, Row>columns. If a default value is not provided, the type ofRow[CName]remains a mystery to typescript and the entire row must be provided explicitly as a type parameter between<>.I don't know if its possible to put a type as a field value in the column definition. It might be, with more mapped types hackery, but I don't think it is... Lets try:
We added a constructor type, now we can add another optional field in the definition that node-sql will never look at:
Now we can use jsType instead:
But you still need hackery for JSON objects with specific shapes. Lets try adding that too... From within the module:
Now we can trick typescript into realising whats the type of this JSON object:
Its not important what the function returns, its only there to placate TypeScript into accepting the type of the column.
Yes, sql.intColumn and other types of columns would have to be added to node-sql. We could perhaps send a PR for it and if @brianc is okay with it he could merge it. They're just small things that would make it easier and more ergonomic to model the library with typescript... I mean the above hacks work too, they are just annoying and error prone (what if we use dataType int with jsType string? Chaos!)
hasis from anydb-sql, it was sort of a failed experiment to model relationships. Feel free to ignore it 😀One of these days, I'm hoping I'll have the chance to clean all this up and contribute proper typings... but right now I can't
3n-mb commentedon Apr 28, 2017
@spion thank you for this piece, it really is useful in the second form, i.e. I am now using it this way, love it so far, in comparison to other ... non-options, in comparison.
I posted code in its entirely, so that other folks may copy and use it directly, buying us time.
For the future, I think that in column interface, things like
equalsshould be usingTthat is already with the column. You have all of ground work done. At least it seems so.spion commentedon Apr 28, 2017
@3n-mb sorry I started editing my original comment and came up with another hack that almost gets the definitions where you wanted them to be (the only caveat is you need to put the JSONObject function somewhere - probably not in the sql module but something like
sql-toolsmaybe - and import it to create new object types)edit: actually individual types can be in a separate module called sql-types or something like that. They would generate column definitions with the appropriate
dataTypefor your database... and include all the type goodies that let TS infer what the column contains.I'm really excited to polish this up a little more... as soon as I find the chance!
Strate commentedon Apr 28, 2017
It would be really good if we can somehow "export" information about selected columns, to achieve typecheck for query result.
3n-mb commentedon Apr 29, 2017
@Strate let try a little hack to pick type for variable, into which result will be placed.
First, let's take example table:
then, let's take a particular query we want to make:
before we jump
toQuery(), we need to arrest type of thisQuery<T>.@spion did magic here, and query's generic type will be in this example something along the lines
T = { user_id: string } & { params: object|undefined }. So, to extract it, we add a phantom field tointerface Query<T>:expanding our example:
Try to use it, share your opinion.
Note that I have introduced record's type in the very front, and seeded with its type into
sql.define<...>(). Initially, I thought this way is too typing-consuming, but now, after use, I realize that this is the the more lazy way of writing, cause (a) sooner or later you will want to have record type, (b) typing inside define isCtrl+Spacedriven activity, (c) any renaming will take all correct places anyway, and (d) reading explicit js type for whole record is easier.3n-mb commentedon Apr 29, 2017
Suggestion for types for column methods
As for types for
equals()and others, I changed their incoming types ininterface Column:It works for me, so far. @spion do you think there may be other unforeseen things here? Or can this be done better?
selectDeep question
@spion is
Queryable.selectDeep(...)from node-sql, or from anydb-sql ?I am slowly groking this. I can see have name-as-type in a column helps, for example to get query result (previous comment). Table's name is used in selectDeep. Is it used elsewhere? Or do you have another plan for it?
Definitions, round three, adding some more node-sql's own things
spion commentedon Apr 30, 2017
Yup,
equalslooks good.regarding
select(column1, column2)it should simply work and generate correct new row types without any extra work. It just needs to be removed from the definition of Table as its a duplicate (justselect<U>(...nodes:any[]):Query<U>, the other overload that has no arguments is fine). It should be correctly provided already byQueryable<T>.The same corrections need to be done for
SubQuery<T>.Another thing,
Queryable<T>only has overloads up to 3 columns, might be a good idea to add support for bigger select statements (9 columns ought to be enough for everyone?)selectDeepis added by anydb-sql and it lets you select multiple tables from a join query. It can be safely left out.3n-mb commentedon Apr 30, 2017
Adding types to update
So far, in
type Tablewe hadupdate(o: any): ModifyingQuery, i.e. no constraining for incoming types.Suggestion
Let's make the following type:
(note question mark for making it partial)
and use it for update argument in
type Table:Sample use
With this modification, given sample table:
typing checks what one puts in update object both for keys and value types:
Writing an update also becomes
Ctrl+Space-driven activity :)3n-mb commentedon Apr 30, 2017
@spion have you added
Nameparameter totype Tableto havedeepSelect?Without
selectDeep, I tried to removeNameparameter. It simplifies things a bit, but clear naming of type in editor is gone, and editor's help becomes less informative. So, even though,Table's name type isn't used likeColumn's name, we better keep it for decoration of code-reading activity.27 remaining items
zenlor commentedon Mar 26, 2018
jayarjo commentedon Apr 24, 2020
Still not solved? Oh my. What if want to generate an insert query for some generic table. How do I safely type that, when I do not even know what the types of those tables are?
3n-mb commentedon Apr 24, 2020
@jayarjo what precisely do you mean?
I use existing typing, and I use it constantly to ensure strict setups of db's. Typing really helps. Start with definition of table, and everything else is checked automagically.
Are you ask about task not being closed. Do you have an impression that there is no typing?
jayarjo commentedon Apr 25, 2020
@3n-mb I cannot finish definition of the table.
I do not know beforehand what the keys of the object will be. I just want to generate the insert query. Suggestions?
3n-mb commentedon Apr 25, 2020
@jayarjo can you flesh it this out a bit more in code snippets of how you want to see things.
This sounds to me like an exercise in flexibility of TypeScript typing mechanism. Do you just put any, or figure it with typeof and other tricks.
jayarjo commentedon Apr 26, 2020
@3n-mb I need to be able to generate an sql for insert (or any other type) query out of totally generic tableName and array of column names. Something like:
where
columnsarray is dynamic and values can be arbitrary.My impression is that it is not possible, at the moment.
3n-mb commentedon Apr 26, 2020
@jayarjo Have you tried the following partial release of type strictness, assuming also that tableName and columns are not known at time of ts' compilation:
Note that type constraint on table name value is simply enforcing strictness (it saved me once already 😄 ). But putting
'any-name'in type does nothing, cause TypeScript's types exist only when you write code, and not when code (js) runs.jayarjo commentedon May 6, 2020
@3n-mb not sure what that does, but it didn't work.
3n-mb commentedon May 6, 2020
@jayarjo give more context. How is table consumed/used? What doesn't work precisely?
If you have any sensitive elements in code, just strip/replace them, and show context in which you want to use this. Also, what is you typescript version?
zenlor commentedon May 9, 2020
@jayarjo
You need to provide the needed type, a
Object.keys(x)is not enough, you will, at least need to cast it to aColumnDefinitionjayarjo commentedon May 9, 2020
It's too much hassle, really. I simply wrote my own query generator. Five lines - that's it. You guys overcomplicate.
3n-mb commentedon May 9, 2020
@jayarjo I look at types not as a hassle, but as a fun exercise of using very flexible Typescript type system.
Now, I will try to narrow your statement about "too much hassle", as to in your particular case.
In my org you can't commit a db code that is not also vetted in some form by compiler on top of regular reviews -- data security, correctness, etc. Hence, I am interested in cases that require deviation from 100% type strictness.
Can I ask you again, @jayarjo to provide more code. We have spent time to consider your questions. Can you extend the same kindness back to us? Thank you in advance.
jayarjo commentedon May 10, 2020
@3n-mb I cannot provide my code, sorry. But what I basically did is that I wrote a generic data seeder using pg-structure and faker that generates arbitrary amount of fake seed data, taking into account structure of the given database, types of the columns, format, length, etc. It is actually interesting if there's anything you can recommend for such use case?
3n-mb commentedon May 10, 2020
@jayarjo
jayarjo commentedon May 11, 2020
@3n-mb no man, you over complicate. And apparently not only in tech. I described my case in quite a detail. Not sure what to add. I doubt that implementation will help to add any context.