├── .nvmrc ├── .gitignore ├── .prettierignore ├── .gitlab-ci.yml ├── .prettierrc ├── src ├── public │ ├── db │ │ ├── index.ts │ │ ├── mongo.ts │ │ ├── utils.ts │ │ ├── cockroach.ts │ │ ├── mysql.ts │ │ └── postgresql.ts │ ├── fields │ │ ├── unsupported.ts │ │ ├── scalars.ts │ │ ├── compounds.ts │ │ ├── relations.ts │ │ └── enums.ts │ ├── mixin.ts │ ├── modifiers.ts │ └── model.ts ├── types │ ├── index.ts │ ├── columns.ts │ ├── mixins.ts │ ├── blocks.ts │ ├── utils.ts │ ├── config.ts │ ├── modifiers.ts │ ├── fields.ts │ └── types.ts ├── codegen │ ├── block.ts │ ├── enum.ts │ ├── transform.ts │ ├── modifiers.ts │ ├── model.ts │ ├── lib │ │ ├── json.ts │ │ ├── dedent.ts │ │ └── pipe.ts │ ├── align.ts │ ├── index.ts │ ├── column.ts │ └── validate.ts ├── index.ts └── __tests__ │ ├── example.ts │ ├── schema.ts │ ├── __snapshots__ │ └── index.spec.ts.snap │ └── index.spec.ts ├── tsconfig.spec.json ├── tsconfig.json ├── jest.config.js ├── package.json ├── DEMO.md ├── CHANGELOG.md ├── README.md └── LICENSE /.nvmrc: -------------------------------------------------------------------------------- 1 | v17.1.0 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | dist 4 | hidden 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | **/schema.ts 2 | **/*schema.ts 3 | **/*.md 4 | example.ts 5 | 6 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | run: 2 | stage: test 3 | image: node:latest 4 | script: 5 | - yarn install 6 | - yarn test 7 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "arrowParens": "avoid", 5 | "printWidth": 80 6 | } 7 | -------------------------------------------------------------------------------- /src/public/db/index.ts: -------------------------------------------------------------------------------- 1 | export { default as Mongo } from './mongo'; 2 | export { default as MySql } from './mysql'; 3 | export { default as Postgres } from './postgresql'; 4 | export { default as Cockroach } from './cockroach'; 5 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from './config'; 2 | export * from './modifiers'; 3 | export * from './columns'; 4 | export * from './types'; 5 | export * from './mixins'; 6 | export * as Fields from './fields'; 7 | export * as Blocks from './blocks'; 8 | -------------------------------------------------------------------------------- /src/types/columns.ts: -------------------------------------------------------------------------------- 1 | import { Modifier } from './modifiers'; 2 | import { Type } from './types'; 3 | 4 | // Physical column in the database 5 | export type Column = { 6 | name: string; 7 | type: T; 8 | modifiers: Modifier[]; 9 | }; 10 | -------------------------------------------------------------------------------- /src/public/db/mongo.ts: -------------------------------------------------------------------------------- 1 | import { db } from './utils'; 2 | 3 | // https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#postgresql 4 | 5 | const _ = db('mongodb'); 6 | 7 | export default { 8 | ObjectId: _.String('ObjectId'), 9 | String: _.String('String'), 10 | }; 11 | -------------------------------------------------------------------------------- /src/codegen/block.ts: -------------------------------------------------------------------------------- 1 | // Creates a nice header string 2 | export const header = (name: string, len: number = 80): string => 3 | `// ${name} ${'-'.repeat(len - name.length)}`; 4 | 5 | // Creates a Block element string 6 | export const block = (name: string, content: string): string => 7 | [`${name} {`, content, `}`].join('\n'); 8 | -------------------------------------------------------------------------------- /src/public/fields/unsupported.ts: -------------------------------------------------------------------------------- 1 | import * as Types from '../../types'; 2 | 3 | export const Unsupported = >( 4 | name: string, 5 | ...modifiers: Types.Modifier<'Unsupported', M>[] 6 | ) => ({ 7 | type: 'Unsupported' as const, 8 | modifiers: [{ type: 'unsupported' as const, value: name }, ...modifiers], 9 | }); 10 | -------------------------------------------------------------------------------- /src/types/mixins.ts: -------------------------------------------------------------------------------- 1 | import { Fields, Type } from '.'; 2 | import { Column } from './columns'; 3 | 4 | export type Mixin = { 5 | Field: ( 6 | name: string, 7 | type: Fields.Field, 8 | comment?: string, 9 | ) => Mixin; 10 | Block: ( 11 | type: Fields.Field, 12 | comment?: string, 13 | ) => Mixin; 14 | columns: Column[]; 15 | }; 16 | -------------------------------------------------------------------------------- /src/codegen/enum.ts: -------------------------------------------------------------------------------- 1 | import * as Types from '../types'; 2 | import { nonNullable } from '../types/utils'; 3 | import { block } from './block'; 4 | import { column } from './column'; 5 | import { extractComments } from './model'; 6 | 7 | export const enumeration = (e: Types.Blocks.Enum): string => { 8 | const [comments, columns] = extractComments(e.columns); 9 | 10 | return [comments, block(`enum ${e.name}`, columns.map(column).join('\n'))] 11 | .filter(nonNullable) 12 | .join('\n') 13 | .trim(); 14 | }; 15 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "esnext", 5 | "jsx": "react", 6 | "sourceMap": false, 7 | "experimentalDecorators": true, 8 | "noImplicitUseStrict": true, 9 | "resolveJsonModule": true, 10 | "removeComments": true, 11 | "moduleResolution": "node", 12 | "esModuleInterop": true, 13 | "lib": ["es2017", "dom"], 14 | "typeRoots": ["node_modules/@types", "src/@types"] 15 | }, 16 | "exclude": ["node_modules", "out", ".next"] 17 | } 18 | -------------------------------------------------------------------------------- /src/types/blocks.ts: -------------------------------------------------------------------------------- 1 | import { Column } from './columns'; 2 | 3 | // A Prisma block level element 4 | export type BlockType = 'model' | 'enum'; 5 | export type Block = { 6 | name: string; 7 | type: T; 8 | columns: T extends 'enum' ? Column<'EnumKey' | 'Comment'>[] : Column[]; 9 | }; 10 | 11 | export type Model = Block<'model'>; 12 | export type Enum = Block<'enum'>; 13 | 14 | export function isEnum(block: Block): block is Block<'enum'> { 15 | return block.type == 'enum'; 16 | } 17 | 18 | export function isModel(block: Block): block is Block<'model'> { 19 | return block.type == 'model'; 20 | } 21 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "esnext", 5 | "jsx": "react", 6 | "sourceMap": false, 7 | "experimentalDecorators": true, 8 | "noImplicitUseStrict": true, 9 | "removeComments": true, 10 | "moduleResolution": "node", 11 | "resolveJsonModule": true, 12 | "esModuleInterop": true, 13 | "lib": ["es2017", "dom"], 14 | "typeRoots": ["node_modules/@types", "src/@types"], 15 | "declaration": true, 16 | "outDir": "./dist" 17 | }, 18 | "include": ["src/**/*"], 19 | "exclude": ["node_modules", "out", ".next", "src/__tests__/**/*"] 20 | } 21 | -------------------------------------------------------------------------------- /src/public/mixin.ts: -------------------------------------------------------------------------------- 1 | import { Mixin as TMixin } from '../types'; 2 | import { Model } from './model'; 3 | 4 | // Mixins are simply models that can be composed into other models 5 | // Perhaps it makes sense to just remove these & allow models to be 6 | // arbitrarily extended - but I kind of hate the idea of 'extending' 7 | // & inheritance... this just exposes a couple fields from Models 8 | // to allow for compositional models 9 | 10 | export const Mixin = (): TMixin => { 11 | const model = Model('mixin'); 12 | 13 | return { 14 | Field: model.Field, 15 | Block: model.Block, 16 | columns: model.columns, 17 | }; 18 | }; 19 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | moduleFileExtensions: ['js', 'ts', 'tsx'], 3 | testMatch: ['**/*.(test|spec).(ts|tsx)'], 4 | globals: { 5 | 'ts-jest': { 6 | tsconfig: 'tsconfig.spec.json', 7 | babelConfig: true, 8 | }, 9 | }, 10 | coveragePathIgnorePatterns: ['/node_modules/'], 11 | coverageReporters: ['json', 'lcov', 'text', 'text-summary'], 12 | moduleNameMapper: { 13 | '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': 14 | '/__mocks__/mocks.js', 15 | '\\.(css|less)$': '/__mocks__/mocks.js', 16 | }, 17 | preset: 'ts-jest', 18 | }; 19 | -------------------------------------------------------------------------------- /src/public/fields/scalars.ts: -------------------------------------------------------------------------------- 1 | import * as Types from '../../types'; 2 | 3 | const scalar = 4 | (type: T) => 5 | >(...modifiers: Types.Modifier[]) => ({ 6 | type, 7 | modifiers, 8 | }); 9 | 10 | export const Int = scalar('Int'); 11 | export const String = scalar('String'); 12 | export const Float = scalar('Float'); 13 | export const BigInt = scalar('BigInt'); 14 | export const Bytes = scalar('Bytes'); 15 | export const Boolean = scalar('Boolean'); 16 | export const Json = scalar('Json'); 17 | export const DateTime = scalar('DateTime'); 18 | export const Decimal = scalar('Decimal'); 19 | -------------------------------------------------------------------------------- /src/public/fields/compounds.ts: -------------------------------------------------------------------------------- 1 | import { Types } from '../..'; 2 | import { Fields, Modifier } from '../../types'; 3 | 4 | const compound = 5 | (type: T) => 6 | ( 7 | values: T extends '@@map' ? string : string[], 8 | ...modifiers: Modifier[] 9 | ): Fields.Field => ({ 10 | type, 11 | modifiers: [{ type: 'values', value: values as any }, ...modifiers], 12 | }); 13 | 14 | export const Id = compound('@@id'); 15 | export const Map = compound('@@map'); 16 | export const Index = compound('@@index'); 17 | export const Unique = compound('@@unique'); 18 | export const Fulltext = compound('@@fulltext'); 19 | export const Ignore: Fields.Field<'@@ignore'> = { 20 | type: '@@ignore', 21 | modifiers: [], 22 | }; 23 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './public/modifiers'; 2 | export * from './public/model'; 3 | export * from './public/mixin'; 4 | export * from './public/fields/scalars'; 5 | export * from './public/fields/enums'; 6 | export * from './public/fields/relations'; 7 | export * from './public/fields/unsupported'; 8 | export * as Compound from './public/fields/compounds'; 9 | export * as Types from './types'; 10 | export * from './public/db'; 11 | 12 | import { writeFile } from 'fs/promises'; 13 | import * as Types from './types'; 14 | import codegen from './codegen'; 15 | 16 | export default (config: Types.Config) => { 17 | const { schema, output, time } = codegen(config); 18 | 19 | return writeFile(output, schema, 'utf8') 20 | .then(() => console.log(`Created schema at: ${output} (${time} ms)`)); 21 | } 22 | 23 | export const generate = (config:Types.Config) => codegen(config).output; 24 | 25 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@cwqt/refract", 3 | "version": "1.3.11", 4 | "description": "Generate Prisma from TypeScript", 5 | "author": "cwqt", 6 | "license": "GPL-3.0-or-later", 7 | "main": "dist/index.js", 8 | "types": "dist/index.d.ts", 9 | "files": [ 10 | "/dist" 11 | ], 12 | "scripts": { 13 | "test": "jest", 14 | "test:update": "jest --updateSnapshot", 15 | "build": "tsc" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "git+ssh://git@gitlab.com/cxss/refract.git" 20 | }, 21 | "keywords": [ 22 | "prisma", 23 | "sdk", 24 | "typescript" 25 | ], 26 | "bugs": { 27 | "url": "https://github.com/cwqt/refract/issues" 28 | }, 29 | "publishConfig": { 30 | "access": "public" 31 | }, 32 | "homepage": "https://github.com/cwqt/refract#readme", 33 | "dependencies": {}, 34 | "devDependencies": { 35 | "@types/jest": "^27.4.1", 36 | "@types/node": "^17.0.23", 37 | "jest": "^28.1.0", 38 | "prettier": "^2.6.2", 39 | "ts-jest": "^27.1.4", 40 | "ts-node": "^10.7.0", 41 | "typescript": "^4.6.3" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/public/db/utils.ts: -------------------------------------------------------------------------------- 1 | import { Provider } from '../../types'; 2 | 3 | export type DbModifier< 4 | T extends string, 5 | P extends Provider, 6 | N extends string, 7 | K, 8 | > = { 9 | scalar: T; 10 | provider: P; 11 | value: K; 12 | type: N; 13 | }; 14 | 15 | export const db =

(provider: P) => { 16 | const type = 17 | (scalar: T) => 18 | ( 19 | name: N, 20 | value?: K | undefined, 21 | ): DbModifier => ({ 22 | type: `@db.${provider}.${name}`, 23 | value, 24 | scalar, 25 | provider, 26 | }); 27 | 28 | const BigInt = type('BigInt' as const); 29 | const String = type('String' as const); 30 | const Float = type('Float'); 31 | const Json = type('Json'); 32 | const Decimal = type('Decimal'); 33 | const Bytes = type('Bytes'); 34 | const DateTime = type('DateTime'); 35 | const Boolean = type('Boolean'); 36 | const Int = type('Int'); 37 | 38 | return { 39 | BigInt, 40 | String, 41 | Float, 42 | Json, 43 | Decimal, 44 | Bytes, 45 | DateTime, 46 | Boolean, 47 | Int, 48 | }; 49 | }; 50 | -------------------------------------------------------------------------------- /src/codegen/transform.ts: -------------------------------------------------------------------------------- 1 | import { Column } from '../types/columns'; 2 | import { JsonValue } from './lib/json'; 3 | import { entries } from '../types/utils'; 4 | 5 | // Prisma KV column types 6 | type Primitive = 7 | | Date 8 | | boolean 9 | | number 10 | | string 11 | | true 12 | | false 13 | | BigInt 14 | | JsonValue; 15 | 16 | type Properties = Record | Column>; 17 | 18 | // Converts a Key-Value value into a Prisma KV value string 19 | export const kv = (properties: Properties): string => { 20 | return entries(properties) 21 | .map(([key, value]) => `\t${key} = ${transform(value)}`) 22 | .join('\n'); 23 | }; 24 | 25 | // Converts from Type to Prisma row string 26 | export const transform = (value: Properties[string]): string => { 27 | switch (typeof value) { 28 | case 'string': { 29 | // Test if it matches a function call 30 | if (/^.*\(.*\)$/.test(value)) return value; 31 | 32 | return `"${value}"`; 33 | } 34 | case 'number': 35 | return value.toString(); 36 | case 'boolean': 37 | return value == true ? 'true' : 'false'; 38 | case 'object': 39 | return JSON.stringify(value); 40 | default: 41 | return ''; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /src/public/modifiers.ts: -------------------------------------------------------------------------------- 1 | import * as Types from '../types'; 2 | 3 | export const Default = < 4 | T extends Types.Fields.Scalar, 5 | K extends Types.TypeData[T]['default'], 6 | >( 7 | value: K, 8 | ): Types.Modifier => ({ type: 'default', value }); 9 | 10 | export const Map = < 11 | T extends Types.Fields.Scalar | 'EnumKey' | '@@unique' | '@@index', 12 | K extends Types.TypeData[T]['map'], 13 | >( 14 | value: K, 15 | ): Types.Modifier => ({ type: 'map', value }); 16 | 17 | export const Unique = { 18 | type: 'unique', 19 | value: true, 20 | } as const; 21 | 22 | export const UpdatedAt = { 23 | type: 'updatedAt', 24 | value: true, 25 | } as const; 26 | 27 | export const Nullable = { 28 | type: 'nullable', 29 | value: true, 30 | } as const; 31 | 32 | export const Id = { 33 | type: 'id', 34 | value: true, 35 | } as const; 36 | 37 | export const Ignore = { 38 | type: 'ignore', 39 | value: true, 40 | } as const; 41 | 42 | export const Array = { 43 | type: 'array', 44 | value: true, 45 | } as const; 46 | 47 | export const Raw = (value: string) => ({ type: 'raw' as const, value }); 48 | 49 | export const Limit = ( 50 | value: K, 51 | ): Types.Modifier<'String', 'limit'> => ({ type: 'limit', value }); 52 | -------------------------------------------------------------------------------- /src/types/utils.ts: -------------------------------------------------------------------------------- 1 | export const isDate = (v: any): v is Date => 2 | v instanceof Date && !isNaN(v as any); 3 | 4 | export const isFn = (v: any): v is F => 5 | typeof v == 'function'; 6 | 7 | export const isString = (v: any): v is string => typeof v == 'string'; 8 | 9 | export const isArray = (v: any): v is any[] => Array.isArray(v); 10 | 11 | type Entries = { 12 | [K in keyof T]: [K, T[K]]; 13 | }[keyof T][]; 14 | export const entries = (obj: T): Entries => Object.entries(obj) as any; 15 | 16 | export type UnionToIntersection = ( 17 | U extends any ? (k: U) => void : never 18 | ) extends (k: infer I) => void 19 | ? I 20 | : never; 21 | 22 | export const del = ( 23 | object: T, 24 | key: K, 25 | ): Exclude => (delete object[key as keyof T], object as any); 26 | 27 | export function nonNullable(value: T): value is NonNullable { 28 | return value !== null && value !== undefined; 29 | } 30 | 31 | type Mutable = { -readonly [P in keyof T]: T[P] }; 32 | export const shift = (v: T): T[0] => 33 | (v as Mutable).shift(); 34 | 35 | // expands object types recursively 36 | export type Expand = T extends object 37 | ? T extends infer O 38 | ? { [K in keyof O]: Expand } 39 | : never 40 | : T; 41 | -------------------------------------------------------------------------------- /src/codegen/modifiers.ts: -------------------------------------------------------------------------------- 1 | import { Modifier } from '../types/modifiers'; 2 | import { Type } from '../types/types'; 3 | import { transform } from './transform'; 4 | 5 | // TODO: less shitty way of doing this 6 | export const modifier = ( 7 | type: T, 8 | modifier: Modifier, 9 | ): string => { 10 | // @db.TinyInt etc. modifiers 11 | if ((modifier.type as string).startsWith('@')) { 12 | // this is rapidly deteriorating lmao 13 | const type = (modifier.type as string).split('.').pop(); 14 | return `@db.${type}${ 15 | Array.isArray(modifier.value) 16 | ? !modifier.value.length || 17 | modifier.value.every(item => item == undefined) 18 | ? '' 19 | : `(${modifier.value.join(', ')})` 20 | : (modifier.value as any) == undefined 21 | ? '' 22 | : `(${modifier.value})` 23 | }`; 24 | } 25 | 26 | // Non @db modifiers 27 | switch (modifier.type) { 28 | case 'default': 29 | return `@default(${ 30 | type == 'Enum' ? modifier.value : transform(modifier.value) 31 | })`; 32 | case 'id': 33 | return `@id`; 34 | case 'unique': 35 | return '@unique'; 36 | case 'updatedAt': 37 | return '@updatedAt'; 38 | case 'ignore': 39 | return '@ignore'; 40 | case 'map': 41 | return `@map("${modifier.value}")`; 42 | case 'unsupported': 43 | return `("${modifier.value}")`; 44 | case 'raw': 45 | return modifier.value as unknown as string; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /src/codegen/model.ts: -------------------------------------------------------------------------------- 1 | import * as Types from '../types'; 2 | import { nonNullable } from '../types/utils'; 3 | import { alignFields } from './align'; 4 | import { block } from './block'; 5 | import { column } from './column'; 6 | 7 | export const model = (model: Types.Blocks.Model): string => { 8 | const [comments, columns] = extractComments(model.columns); 9 | 10 | return [ 11 | comments, 12 | block(`model ${model.name}`, alignFields(columns.map(column).join('\n'))), 13 | ] 14 | .filter(nonNullable) 15 | .join('\n') 16 | .trim(); 17 | }; 18 | 19 | export const extractComments = ( 20 | columns: Types.Column[], 21 | ): [outside: string, columns: Types.Column[]] => { 22 | return [ 23 | // All comment rows for a model are placed outside the model block def 24 | columns 25 | .filter(c => c.type == 'Comment') 26 | .map(c => `// ${c.modifiers[0].value}`) 27 | .join('\n'), 28 | 29 | columns 30 | // Remove Comment rows to prevent re-insertion 31 | .filter(c => c.type !== 'Comment') 32 | // Shift all comment modifiers to be on their own row as a Comment column 33 | .reduce( 34 | (cols, column) => [ 35 | ...cols, 36 | ...column.modifiers 37 | .filter(c => c.type == 'comment') 38 | .map(c => ({ 39 | name: 'comment', 40 | type: 'Comment', 41 | modifiers: [c], 42 | })), 43 | column, 44 | ], 45 | [], 46 | ), 47 | ]; 48 | }; 49 | -------------------------------------------------------------------------------- /src/codegen/lib/json.ts: -------------------------------------------------------------------------------- 1 | // https://github.com/sindresorhus/type-fest/blob/main/source/basic.d.ts 2 | /** 3 | Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). 4 | @category Class 5 | */ 6 | export type Class = Constructor< 7 | T, 8 | Arguments 9 | > & { prototype: T }; 10 | 11 | /** 12 | Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). 13 | @category Class 14 | */ 15 | export type Constructor = new ( 16 | ...arguments_: Arguments 17 | ) => T; 18 | 19 | /** 20 | Matches a JSON object. 21 | This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`. 22 | @category JSON 23 | */ 24 | export type JsonObject = { [Key in string]?: JsonValue }; 25 | 26 | /** 27 | Matches a JSON array. 28 | @category JSON 29 | */ 30 | export type JsonArray = JsonValue[]; 31 | 32 | /** 33 | Matches any valid JSON primitive value. 34 | @category JSON 35 | */ 36 | export type JsonPrimitive = string | number | boolean | null; 37 | 38 | /** 39 | Matches any valid JSON value. 40 | @see `Jsonify` if you need to transform a type to one that is assignable to `JsonValue`. 41 | @category JSON 42 | */ 43 | export type JsonValue = JsonPrimitive | JsonObject | JsonArray; 44 | -------------------------------------------------------------------------------- /src/__tests__/example.ts: -------------------------------------------------------------------------------- 1 | import Refract, { 2 | Boolean, DateTime, Default, 3 | Enum, 4 | Fields, Id, 5 | Int, 6 | Key, ManyToOne, Mixin, 7 | Model, 8 | MySql as db, 9 | Nullable, OneToMany, References, 10 | String, 11 | Unique, UpdatedAt, 12 | Types 13 | } from '..'; 14 | 15 | const datasource: Types.Config["datasource"] = { provider: "mysql", url: 'env("URL")' } 16 | const generators: Types.Config['generators'] = [ 17 | { 18 | name: 'client', 19 | provider: 'prisma-client-js', 20 | binaryTargets: [ 21 | 'native', 22 | 'rhel-openssl-1.0.x', 23 | 'linux-arm64-openssl-1.0.x', 24 | 'darwin-arm64', 25 | ], 26 | previewFeatures: ['referentialIntegrity'], 27 | }, 28 | ]; 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | const Base = Mixin() 40 | .Field("id", Int(Id, Default("autoincrement()"))) 41 | .Field("createdAt", DateTime(Default("now()"))) 42 | .Field("updatedAt", DateTime(Default("now()"), UpdatedAt)); 43 | 44 | const User = Model("User").Mixin(Base); 45 | const Post = Model("Post").Mixin(Base); 46 | 47 | const Role = Enum("Role", Key("USER"), Key("ADMIN")); 48 | 49 | User 50 | .Field("email", String(Unique)) 51 | .Field("name", String(Nullable)) 52 | .Field("role", Role("USER")) 53 | .Relation("posts", OneToMany(Post)); 54 | 55 | Post 56 | .Field("published", Boolean(Default(false))) 57 | .Field("title", String(db.VarChar(255))) 58 | .Relation("author", ManyToOne(User, Fields("authorId"), References("id"), Nullable)) 59 | .Field("authorId", Int(Nullable)); 60 | 61 | 62 | Refract({ schema: [User, Post, Role], datasource, generators }) 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/codegen/align.ts: -------------------------------------------------------------------------------- 1 | import { nonNullable } from '../types/utils'; 2 | 3 | // Align contents of a datasource/generator to that of the longest column 4 | export const alignKv = (value: string): string => { 5 | const lines = value.split('\n'); 6 | const delimiter = '='; 7 | 8 | const max = 9 | Math.max(...lines.map(l => l.trim().split(delimiter).shift().length)) + 1; 10 | 11 | return lines 12 | .map(line => line.split(delimiter)) 13 | .map(([head, ...rest]) => 14 | [head.padEnd(max), delimiter, ...rest.map(v => v.trim())].join(' '), 15 | ) 16 | .join('\n'); 17 | }; 18 | 19 | // Align contents of a model to that of the longest column 20 | export const alignFields = (value: string): string => { 21 | const lines = value.split('\n'); 22 | 23 | const [maximumColumnName, maximumColumnType] = lines 24 | .map(l => l.split(' ')) 25 | .reduce( 26 | ([maxName, maxType], [name, type]) => [ 27 | Math.max(maxName, name.length), 28 | Math.max(maxType, (type ?? '').length), 29 | ], 30 | [0, 0], 31 | ); 32 | 33 | return lines 34 | .map(line => line.split(' ')) 35 | .map(([columnName, columnType, ...rest]) => { 36 | return ( 37 | [n => n.startsWith('@@'), n => n == '//'].some(fn => 38 | fn(columnName.trim()), 39 | ) 40 | ? [columnName, columnType, ...rest].filter(nonNullable) 41 | : [ 42 | columnName.padEnd(maximumColumnName + 1), 43 | columnType ? columnType.padEnd(maximumColumnType + 1) : '', 44 | ...rest.map(v => v.trim()), 45 | ] 46 | ).join(' '); 47 | }) 48 | .map(v => v.trimEnd()) 49 | .join('\n'); 50 | }; 51 | 52 | function pp(columnName: any): any { 53 | console.log(JSON.stringify(columnName)); 54 | } 55 | -------------------------------------------------------------------------------- /src/public/db/cockroach.ts: -------------------------------------------------------------------------------- 1 | import { db } from './utils'; 2 | 3 | // https://www.prisma.io/docs/concepts/database-connectors/cockroachdb 4 | const _ = db('cockroachdb'); 5 | 6 | // prettier-ignore 7 | export default { 8 | Int8: _.BigInt('Int8'), 9 | Bool: _.Boolean('Bool'), 10 | TimeStamp: (precision?: number) => _.DateTime('Timestamp', precision), 11 | Timestamptz: (precision?: number) => _.DateTime('Timestamptz', precision), 12 | Time: (precision?: number) => _.DateTime('Time', precision), 13 | Timetz: (precision?: number) => _.DateTime('Timetz', precision), 14 | Decimal: (precision: number, scale: number) => _.Decimal('Decimal', [precision, scale]), 15 | Float4: _.Float('Float4'), 16 | Float8: _.Float('Float8'), 17 | Int2: _.Int('Int2'), 18 | Int4: _.Int('Int4'), 19 | Char: (length?: number) => _.String('Char', length), 20 | CatalogSingleChar: _.String('CatalogSingleChar'), 21 | String: _.String('String'), 22 | Date: _.DateTime('Date'), 23 | Inet: _.String('Inet'), 24 | Bit: (length?: number) => _.String('Bit', length), 25 | VarBit: (length?: number) => _.String('VarBit', length), 26 | Oid: _.Int('Oid'), 27 | Uuid: _.String('Uuid'), 28 | JsonB: _.Json('JsonB'), 29 | }; 30 | -------------------------------------------------------------------------------- /src/public/db/mysql.ts: -------------------------------------------------------------------------------- 1 | import { db } from './utils'; 2 | 3 | // https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#mysql 4 | const _ = db('mysql'); 5 | 6 | // prettier-ignore 7 | export default { 8 | Char: (value: number) => _.String('Char', value), 9 | VarChar: (value: number) => _.String('VarChar', value), 10 | TinyInt: (value: number) => _.Boolean('TinyInt', value), 11 | UnsignedBigInt: _.BigInt('UnsignedBigInt'), 12 | BigInt: _.BigInt('BigInt'), 13 | SmallInt: _.BigInt('SmallInt'), 14 | UnsignedSmallInt: _.Int('UnsignedSmallInt'), 15 | MediumInt: _.Int('MediumInt'), 16 | UnsignedMediumInt: _.Int('UnsignedMediumInt'), 17 | Year: _.Int('Year'), 18 | Float: _.Float('Float'), 19 | Double: _.Float('Double'), 20 | VarBinary: _.Bytes('VarBinary'), 21 | LongBlob: _.Bytes('LongBlog'), 22 | TinyBlob: _.Bytes('TinyBlob'), 23 | MediumBlob: _.Bytes('MediumBlob'), 24 | Blob: _.Bytes('Blob'), 25 | Binary: _.Bytes('Binary'), 26 | Bit: (value: number) => _.Bytes('Bit', value), 27 | Date: (value:number) => _.DateTime('Date', value), 28 | DateTime: (value:number) => _.DateTime('DateTime', value), 29 | Timestamp: (value:number) => _.DateTime('Timestamp', value), 30 | Time: (value:number) => _.DateTime('Time', value), 31 | Json: _.Json('Json'), 32 | Text: _.String('Text'), 33 | Decimal: (precision: number, scale: number) => _.Decimal('Decimal', [precision, scale]), 34 | }; 35 | 36 | type Coords = [x: number, y: number]; 37 | -------------------------------------------------------------------------------- /src/codegen/lib/dedent.ts: -------------------------------------------------------------------------------- 1 | // https://github.com/tamino-martinius/node-ts-dedent 2 | export function dedent( 3 | templ: TemplateStringsArray | string, 4 | ...values: unknown[] 5 | ): string { 6 | let strings = Array.from(typeof templ === 'string' ? [templ] : templ); 7 | 8 | // 1. Remove trailing whitespace. 9 | strings[strings.length - 1] = strings[strings.length - 1].replace( 10 | /\r?\n([\t ]*)$/, 11 | '', 12 | ); 13 | 14 | // 2. Find all line breaks to determine the highest common indentation level. 15 | const indentLengths = strings.reduce((arr, str) => { 16 | const matches = str.match(/\n([\t ]+|(?!\s).)/g); 17 | if (matches) { 18 | return arr.concat( 19 | matches.map(match => match.match(/[\t ]/g)?.length ?? 0), 20 | ); 21 | } 22 | return arr; 23 | }, []); 24 | 25 | // 3. Remove the common indentation from all strings. 26 | if (indentLengths.length) { 27 | const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, 'g'); 28 | 29 | strings = strings.map(str => str.replace(pattern, '\n')); 30 | } 31 | 32 | // 4. Remove leading whitespace. 33 | strings[0] = strings[0].replace(/^\r?\n/, ''); 34 | 35 | // 5. Perform interpolation. 36 | let string = strings[0]; 37 | 38 | values.forEach((value, i) => { 39 | // 5.1 Read current indentation level 40 | const endentations = string.match(/(?:^|\n)( *)$/); 41 | const endentation = endentations ? endentations[1] : ''; 42 | let indentedValue = value; 43 | // 5.2 Add indentation to values with multiline strings 44 | if (typeof value === 'string' && value.includes('\n')) { 45 | indentedValue = String(value) 46 | .split('\n') 47 | .map((str, i) => { 48 | return i === 0 ? str : `${endentation}${str}`; 49 | }) 50 | .join('\n'); 51 | } 52 | 53 | string += indentedValue + strings[i + 1]; 54 | }); 55 | 56 | return string; 57 | } 58 | -------------------------------------------------------------------------------- /src/types/config.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | import { Block } from './blocks'; 3 | 4 | export type Provider = 5 | | 'mongodb' 6 | | 'postgresql' 7 | | 'mysql' 8 | | 'sqlite' 9 | | 'sqlserver' 10 | | 'cockroachdb'; 11 | 12 | export type Datasource = { 13 | provider: Provider; 14 | url: string; 15 | shadowDatabaseUrl?: string; 16 | referentialIntegrity?: 'prisma' | 'foreignKeys'; 17 | }; 18 | 19 | type PreviewFeatures = 20 | | 'filterJson' 21 | | 'interactiveTransactions' 22 | | 'fullTextSearch' 23 | | 'referentialIntegrity' 24 | | 'dataProxy' 25 | | 'extendedIndexes' 26 | | 'fullTextIndex' 27 | | 'cockroachdb'; 28 | 29 | export type Generator = { 30 | name: string; 31 | provider: string; 32 | output?: string; 33 | previewFeatures?: PreviewFeatures[]; 34 | engineType?: 'library' | 'binary'; 35 | binaryTargets?: string[]; // TODO: enum 36 | }; 37 | 38 | export type Config = { 39 | datasource: Datasource; 40 | generators: Generator[]; 41 | output?: string; 42 | schema: Block[] | Record; 43 | }; 44 | 45 | export const validate = (config: Config): Config => { 46 | if (config.datasource.referentialIntegrity) { 47 | if ( 48 | !config.generators.some(g => 49 | g.previewFeatures?.includes('referentialIntegrity'), 50 | ) 51 | ) 52 | throw new Error( 53 | "Must have a generator with the 'referentialIntegrity' preview feature enabled to use referential integrity in the datasource", 54 | ); 55 | } 56 | 57 | if (config.datasource.provider == 'mysql') { 58 | if ( 59 | config.generators.some( 60 | g => 61 | g.previewFeatures?.includes('fullTextSearch') && 62 | !g.previewFeatures?.includes('fullTextIndex'), 63 | ) 64 | ) 65 | throw new Error( 66 | 'MySQL Users must include both fullTextSearch & fullTextIndex in the preview features.', 67 | ); 68 | } 69 | 70 | return { 71 | ...config, 72 | output: config.output || path.join(process.cwd(), 'schema.prisma'), 73 | }; 74 | }; 75 | -------------------------------------------------------------------------------- /DEMO.md: -------------------------------------------------------------------------------- 1 | # Demo 2 | 3 | `refract.ts` 4 | 5 | ```typescript 6 | import Refract from '@cwqt/refract'; 7 | import schema from './schema'; 8 | 9 | Refract({ 10 | datasource: { 11 | provider: 'postgresql', 12 | url: process.env.PG_URL, 13 | shadowDatabaseUrl: process.env.PG_SHADOW_URL, 14 | referentialIntegrity: 'prisma', 15 | }, 16 | generators: [ 17 | { 18 | provider: 'prisma-client-js', 19 | previewFeatures: ['referentialIntegrity'], 20 | engineType: 'library', 21 | binaryTargets: ['native'], 22 | }, 23 | ], 24 | output: path.join(process.cwd(), 'myschema.prisma'), 25 | schema, 26 | }); 27 | 28 | // Generate the schema with `npx ts-node refract.ts` 29 | ``` 30 | 31 | `schema.ts` 32 | 33 | 34 | ```typescript 35 | // example from: https://www.prisma.io/docs/concepts/components/prisma-schema#example 36 | 37 | // Enums 38 | const Role = Enum('Role', Key('User', Map('user')), Key('Admin')); 39 | 40 | // Define models first for circular relations 41 | const Post = Model('Post'); 42 | const User = Model('User'); 43 | 44 | // Mixins (think inheritance) 45 | const Timestamps = Mixin() 46 | .Field('createdAt', DateTime(Default('now()'))) 47 | .Field('updatedAt', DateTime(UpdatedAt)); 48 | 49 | User 50 | .Field('id', Int(Id, Default('autoincrement()'))) 51 | .Field('email', String(Unique)) 52 | .Field('name', String(Nullable)) 53 | .Field('role', Role('User')) 54 | .Relation('posts', OneToMany(Post)) 55 | // Use a mixin, adds createdAt & updatedAt columns to Model 56 | .Mixin(Timestamps); 57 | 58 | Post 59 | .Field('id', Int(Id, Default('autoincrement()'))) 60 | // Defaults are type-safe 61 | .Field('published', Boolean(Default(false))) 62 | .Field('title', String(Limit(255))) 63 | .Field('authorId', Int(Nullable)) 64 | // All kinds of relationships 65 | .Relation('author', ManyToOne(User, Fields('authorId'), References('id'), Nullable)) 66 | .Mixin(Timestamps) 67 | // Escape hatch into raw Prisma 68 | .Raw(`@@map("comments")`); 69 | 70 | export default [Role, User, Post]; 71 | ``` 72 | -------------------------------------------------------------------------------- /src/public/db/postgresql.ts: -------------------------------------------------------------------------------- 1 | import { db } from './utils'; 2 | 3 | // https://www.prisma.io/docs/concepts/database-connectors/postgresql 4 | const _ = db('postgresql'); 5 | 6 | // prettier-ignore 7 | export default { 8 | BigInt: _.BigInt('BigInt'), 9 | Boolean: _.Boolean('Boolean'), 10 | Timestamp: (precision?: number) => _.DateTime('Timestamp', precision), 11 | Timestamptz: (precision?: number) => _.DateTime('Timestamptz', precision), 12 | Time: (precision?: number) => _.DateTime('Time', precision), 13 | Timetz: (precision?: number) => _.DateTime('Timetz', precision), 14 | Decimal: (precision?: number, scale?: number) => _.Decimal('Decimal', [precision, scale]), 15 | Real: _.Float('Real'), 16 | DoublePrecision: _.Float('DoublePrecision'), 17 | SmallInt: _.Int('SmallInt'), 18 | Char: (length?: number) => _.String('Char', length), 19 | VarChar: (length?: number) => _.String('VarChar', length), 20 | Money: _.Decimal('Money'), 21 | Text: _.String('Text'), 22 | Date: _.DateTime('Date'), 23 | Inet: _.String('Inet'), 24 | Bit: (length?: number) => _.String('Bit', length), 25 | VarBit: (length?: number) => _.String('VarBit', length), 26 | Oid: _.Int('Oid'), 27 | Uuid: _.String('Uuid'), 28 | Json: _.Json('Json'), 29 | JsonB: _.Json('JsonB'), 30 | ByteA: _.Bytes('ByteA'), 31 | Xml: _.String('Xml'), 32 | Citext: _.String('Citext'), 33 | }; 34 | -------------------------------------------------------------------------------- /src/types/modifiers.ts: -------------------------------------------------------------------------------- 1 | import { Type, TypeData } from './types'; 2 | 3 | // Column modifiers, e.g. @default(), @nullable() etc. 4 | export type Modifier< 5 | T extends Type = Type, 6 | Property extends Modifiers = Modifiers, 7 | > = { type: Property; value: TypeData[T][Property] }; 8 | 9 | export type Modifiers = keyof TypeData[T]; 10 | 11 | // ------------------------------------------------------- 12 | import { Cockroach, Mongo, MySql, Postgres } from '../public/db'; 13 | import { Provider } from './config'; 14 | 15 | type Db = { 16 | mysql: typeof MySql; 17 | mongodb: typeof Mongo; 18 | postgresql: typeof Postgres; 19 | cockroach: typeof Cockroach; 20 | }; 21 | 22 | type DbModifer = { 23 | scalar: string; 24 | type: string; 25 | value: any; 26 | provider: Provider; 27 | }; 28 | 29 | type DbMap = Record DbModifer)>; 30 | 31 | // Converts the Function modifiers to the resulting DbModifiers 32 | type Flatten = { 33 | [index in keyof T]: T[index] extends (...args: any) => DbModifer 34 | ? ReturnType 35 | : T[index]; 36 | }; 37 | 38 | // Flattened version of Db 39 | type FlattenedDb = { [db in keyof Db]: Flatten }; 40 | 41 | // Get DbMap values as a Union for each DbMap 42 | type FlatUnionDb = { 43 | [db in keyof FlattenedDb]: FlattenedDb[db][keyof FlattenedDb[db]]; 44 | }; 45 | 46 | // Flatten again to get rid of the keys & have one big union 47 | type FlatFlatUnion = FlatUnionDb[keyof FlatUnionDb]; 48 | 49 | // Converts the big Union into being grouped by Scalar type (String, Int etc.) 50 | type GroupBy, D extends keyof T> = { 51 | [K in T[D]]: T extends Record ? T : never; 52 | }; 53 | 54 | // Map into union of { type: value } -- { @db.mysql.TinyInt: number } | ... 55 | type Transform> = { 56 | [index in keyof T]: { [i in T[index]['type']]: T[index]['value'] }; 57 | }; 58 | 59 | type Map = Transform>; 60 | 61 | // Merge Map into Scalars 62 | export type MergeDbModifiers = { 63 | // Ignore if not exists in DbMap for db 64 | [type in keyof T]: Map extends { [P in type]: infer _ } 65 | ? T[type] & Map[type] 66 | : T[type]; 67 | }; 68 | -------------------------------------------------------------------------------- /src/codegen/index.ts: -------------------------------------------------------------------------------- 1 | import { performance } from 'perf_hooks'; 2 | import * as Types from '../types'; 3 | import { validate } from '../types'; 4 | import { del, nonNullable } from '../types/utils'; 5 | import { alignKv } from './align'; 6 | import { block, header } from './block'; 7 | import { enumeration } from './enum'; 8 | import { dedent } from './lib/dedent'; 9 | import { pipe } from './lib/pipe'; 10 | import { model } from './model'; 11 | import { kv } from './transform'; 12 | import { validateModel } from './validate'; 13 | 14 | // Takes a Config input & returns a generated Prisma schema file as a string 15 | // which can then be written to a file / formatted by Prisma CLI 16 | export default ( 17 | config: Types.Config, 18 | ): { schema: string; time: number; output: string } => { 19 | const start = performance.now(); 20 | 21 | // Allow direct imports, e.g. `import * as schema from './foo'` 22 | const schema = Array.isArray(config.schema) 23 | ? config.schema 24 | : Object.values(config.schema); 25 | 26 | config = validate({ ...config, schema }); 27 | 28 | const datasource = config.datasource; 29 | const generators = config.generators; 30 | const enums = schema.filter(Types.Blocks.isEnum); 31 | const models = schema.filter(Types.Blocks.isModel); 32 | 33 | const group = (header: string, blocks: string[]): string | null => 34 | blocks.length == 0 ? null : [header, blocks.join('\n\n')].join('\n\n'); 35 | 36 | const generated = dedent( 37 | [ 38 | header('datasource'), 39 | block('datasource db', alignKv(kv(datasource))), 40 | group( 41 | header('generators'), 42 | generators.map(generator => 43 | block( 44 | `generator ${generator.name}`, 45 | alignKv(kv(del(generator, 'name'))), 46 | ), 47 | ), 48 | ), 49 | group(header('enums'), enums.map(enumeration)), 50 | group(header('models'), models.map(pipe(validateModel(config), model))), 51 | ] 52 | .filter(nonNullable) 53 | .flat() 54 | .join('\n\n'), 55 | ); 56 | 57 | const end = performance.now(); 58 | const time = Number((end - start).toFixed(3)); 59 | 60 | return { 61 | time, 62 | output: config.output, 63 | schema: [ 64 | header( 65 | `refract https://github.com/cwqt/refract - generated in ${time} ms`, 66 | ), 67 | generated, 68 | ].join('\n'), 69 | }; 70 | }; 71 | -------------------------------------------------------------------------------- /src/types/fields.ts: -------------------------------------------------------------------------------- 1 | import { Column } from './columns'; 2 | import { Modifier, Modifiers } from './modifiers'; 3 | import { Type, TypeData } from './types'; 4 | import { UnionToIntersection } from './utils'; 5 | import * as Types from './types'; 6 | import { Provider } from './config'; 7 | import { DbModifier } from '../public/db/utils'; 8 | 9 | // Column data-type, String, Int etc. 10 | export type Field = Modifiers> = { 11 | type: T; 12 | modifiers: Modifier[]; 13 | }; 14 | 15 | export type EnumKey = { 16 | name: T; 17 | modifiers: Modifier<'EnumKey'>[]; 18 | }; 19 | 20 | export type Scalar = keyof Types.Scalars; 21 | export type Enum = keyof Types.Enums; 22 | export type Relation = keyof Types.Relations; 23 | export type Compound = keyof Types.Compounds; 24 | 25 | export type Any = Scalar | Relation | Enum | Compound | 'Raw' | 'Unsupported'; 26 | 27 | export type ReferentialAction = 28 | | 'Cascade' 29 | | 'Restrict' 30 | | 'NoAction' 31 | | 'SetNull' 32 | | 'SetDefault'; 33 | 34 | // Top type for columns 35 | type TopColumn = { 36 | name: string; 37 | type: Type; 38 | modifiers: Array<{ 39 | type: keyof UnionToIntersection<{ [type in Type]: TypeData[type] }[Type]>; 40 | value: any; 41 | }>; 42 | }; 43 | 44 | export function isRaw(column: TopColumn): column is Column<'Raw'> { 45 | return column.type == 'Raw'; 46 | } 47 | 48 | export function isComment(column: TopColumn): column is Column<'Comment'> { 49 | return column.type == 'Comment'; 50 | } 51 | 52 | export function isCompound(column: TopColumn): column is Column { 53 | return column.type.startsWith('@@'); 54 | } 55 | 56 | export function isEnumKey(column: TopColumn): column is Column<'EnumKey'> { 57 | return column.type == 'EnumKey'; 58 | } 59 | 60 | export function isEnum(column: TopColumn): column is Column<'Enum'> { 61 | return column.type == 'Enum'; 62 | } 63 | 64 | export function isUnsupported( 65 | column: TopColumn, 66 | ): column is Column<'Unsupported'> { 67 | return column.type == 'Unsupported'; 68 | } 69 | 70 | export function isRelation(column: TopColumn): column is Column { 71 | return ['OneToMany', 'ManyToOne', 'OneToOne'].includes(column.type); 72 | } 73 | 74 | export function isDbModifier( 75 | column: Modifier, 76 | ): column is DbModifier { 77 | return (column.type as string).startsWith('@db'); 78 | } 79 | 80 | export function isScalar(column: TopColumn): column is Column { 81 | return ( 82 | typeof column == 'object' && 83 | [ 84 | isRelation(column), 85 | isEnumKey(column), 86 | isEnum(column), 87 | isCompound(column), 88 | ].every(v => v == false) 89 | ); 90 | } 91 | -------------------------------------------------------------------------------- /src/types/types.ts: -------------------------------------------------------------------------------- 1 | import { Types } from '..'; 2 | import { JsonValue } from '../codegen/lib/json'; 3 | import { Model } from './blocks'; 4 | import { ReferentialAction, Scalar } from './fields'; 5 | import { MergeDbModifiers } from './modifiers'; 6 | 7 | type Append = { [index in keyof T]: T[index] & K }; 8 | 9 | export type Scalars = Append< 10 | { 11 | String: { 12 | unique?: true; 13 | id?: true; 14 | default?: string | 'auto()'; 15 | limit?: number; 16 | }; 17 | Int: { 18 | unique?: true; 19 | id?: true; 20 | default?: 'cuid()' | 'autoincrement()' | 'uuid()' | number; 21 | }; 22 | Float: { 23 | unique?: true; 24 | default?: number; 25 | }; 26 | BigInt: { 27 | unique?: true; 28 | default?: BigInt; 29 | }; 30 | Bytes: { 31 | unique?: true; 32 | default?: never; 33 | }; 34 | Decimal: { 35 | unique?: true; 36 | default?: number; 37 | }; 38 | Boolean: { 39 | unique?: true; 40 | default?: boolean; 41 | }; 42 | DateTime: { 43 | default?: 'now()'; 44 | updatedAt?: true; 45 | }; 46 | Json: { default?: JsonValue }; 47 | }, 48 | { 49 | nullable?: boolean; 50 | map?: string; 51 | ignore?: true; 52 | raw?: string; 53 | array?: true; 54 | comment?: string; 55 | } 56 | >; 57 | 58 | export type Enums = { 59 | Enum: { 60 | id?: true; 61 | nullable?: boolean; 62 | default?: string; 63 | ignore?: true; 64 | comment?: string; 65 | 66 | // Enum of which this is from 67 | enum: string; 68 | }; 69 | // An entry in the enum, e.g. Enum("name", Key("Id", Map("_id"))) 70 | EnumKey: { 71 | map?: string; 72 | comment?: string; 73 | }; 74 | }; 75 | 76 | export type Reference = [ 77 | reference: string, 78 | scalar?: Types.Fields.Field<'Int'> | Types.Fields.Field<'String'>, 79 | ]; 80 | 81 | export type Relations = Append< 82 | { 83 | OneToMany: {}; 84 | OneToOne: { 85 | fields?: string[] | Reference; 86 | references?: string[]; 87 | onUpdate?: ReferentialAction; 88 | onDelete?: ReferentialAction; 89 | nullable?: boolean; 90 | }; 91 | ManyToOne: { 92 | fields: string[] | Reference; 93 | references: string[]; 94 | onUpdate?: ReferentialAction; 95 | onDelete?: ReferentialAction; 96 | nullable?: boolean; 97 | }; 98 | }, 99 | { name?: string; model: Model; comment?: string } 100 | >; 101 | 102 | export type Compounds = Append< 103 | { 104 | ['@@id']: {}; 105 | ['@@unique']: { map: string }; 106 | ['@@index']: { map: string }; 107 | ['@@ignore']: {}; 108 | ['@@map']: {}; 109 | ['@@fulltext']: {}; 110 | }, 111 | { values: string[]; comment?: string } 112 | >; 113 | 114 | export type TypeData = MergeDbModifiers & 115 | Compounds & 116 | Enums & 117 | Relations & { 118 | Comment: { value: string }; 119 | Raw: { value: string }; 120 | Unsupported: { unsupported: string; nullable?: boolean }; 121 | }; 122 | 123 | // All possible column datatypes & their accepted modifiers/parameters 124 | export type Type = keyof TypeData; 125 | -------------------------------------------------------------------------------- /src/public/model.ts: -------------------------------------------------------------------------------- 1 | import * as Types from '../types'; 2 | import { isScalar } from '../types/fields'; 3 | 4 | // Don't really care about the `as unknown` casts too much 5 | // as long as the public interface is type-safe.... 6 | 7 | // Self-referential type 8 | type Model = { 9 | Mixin: (...mixins: Types.Mixin[]) => Model; 10 | Raw: (value: string) => Model; 11 | Relation: ( 12 | name: string, 13 | type: Types.Fields.Field, 14 | comment?: string, 15 | ) => Model; 16 | Field: ( 17 | name: string, 18 | type: Types.Fields.Field, 19 | comment?: string, 20 | ) => Model; 21 | Block: ( 22 | type: Types.Fields.Field, 23 | comment?: string, 24 | ) => Model; 25 | } & Types.Blocks.Model; 26 | 27 | export const Model = (name: string, comment?: string): Model => 28 | new $Model(name, comment); 29 | 30 | export class $Model implements Types.Blocks.Model, Model { 31 | name: string; 32 | type: 'model' = 'model'; 33 | columns: Types.Column[] = []; 34 | 35 | constructor(name: string, comment?: string) { 36 | this.name = name; 37 | 38 | if (comment) { 39 | this.columns.push({ 40 | name: 'comment', 41 | type: 'Comment' as const, 42 | modifiers: [{ type: 'value', value: comment }], 43 | } as Types.Column); 44 | } 45 | } 46 | 47 | Mixin(...mixins: Types.Mixin[]) { 48 | mixins.forEach(mixin => 49 | this.columns.push(...(mixin.columns as Types.Column[])), 50 | ); 51 | 52 | return this; 53 | } 54 | 55 | Raw(value: string) { 56 | const modifier: Types.Modifier<'Raw', 'value'> = { type: 'value', value }; 57 | const column: Types.Column<'Raw'> = { 58 | name: 'raw', 59 | type: 'Raw' as const, 60 | modifiers: [modifier], 61 | }; 62 | 63 | this.columns.push(column as Types.Column); 64 | return this; 65 | } 66 | 67 | Relation( 68 | name: string, 69 | type: Types.Fields.Field, 70 | comment?: string, 71 | ) { 72 | if (comment) 73 | type.modifiers.push({ type: 'comment', value: comment } as any); 74 | 75 | // Fields('column', Int()) 76 | const fields = type.modifiers.find(m => m.type == 'fields'); 77 | if (isScalar(fields?.value?.[1])) { 78 | this.Field(fields.value[0], fields.value[1]); 79 | // remove scalar from modifiers pre-codegen 80 | (fields.value as unknown as any[]).pop(); 81 | } 82 | 83 | this.columns.push({ name, ...type } as unknown as Types.Column); 84 | return this; 85 | } 86 | 87 | Field( 88 | name: string, 89 | type: Types.Fields.Field, 90 | comment?: string, 91 | ) { 92 | if (comment) 93 | type.modifiers.push({ type: 'comment', value: comment } as any); 94 | 95 | this.columns.push({ name, ...type } as unknown as Types.Column); 96 | return this; 97 | } 98 | 99 | Block( 100 | type: Types.Fields.Field, 101 | comment?: string, 102 | ) { 103 | if (comment) 104 | type.modifiers.push({ type: 'comment', value: comment } as any); 105 | 106 | this.columns.push(type as unknown as Types.Column); 107 | return this; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/__tests__/schema.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Boolean, 3 | Compound, 4 | DateTime, 5 | Decimal, 6 | Default, 7 | Enum, 8 | Fields, 9 | Float, 10 | Id, 11 | Int, 12 | Key, 13 | Limit, 14 | ManyToOne, 15 | Map, 16 | Mixin, 17 | Model, 18 | MySql as db, 19 | Nullable, 20 | OnDelete, 21 | OneToMany, 22 | OneToOne, 23 | OnUpdate, 24 | Raw, 25 | References, 26 | String, 27 | Unique, 28 | Unsupported, 29 | UpdatedAt, 30 | } from '..'; 31 | 32 | // roughly from: https://www.prisma.io/docs/concepts/components/prisma-schema#example 33 | 34 | // with comment 35 | const Role = Enum( 36 | 'Role', 37 | 'This is the Role Enum', 38 | Key('ADMIN', Map('admin'), 'This is the admin role'), 39 | Key('USER', Map('user')), 40 | Key('OWNER', Map('owner'), 'This is the owner role'), 41 | ); 42 | 43 | // without comment 44 | const Foo = Enum('Foo', Key('Bar'), Key('Baz')); 45 | 46 | const Post = Model('Post'); 47 | const User = Model('User', 'This is the User model'); 48 | const Star = Model('Star'); 49 | 50 | // prettier-ignore 51 | const Timestamps = Mixin() 52 | .Field('createdAt', DateTime(Default('now()'))) 53 | .Field('updatedAt', DateTime(UpdatedAt, db.Date(6))) 54 | .Block(Compound.Index(["mixin", "index"])) 55 | 56 | // prettier-ignore 57 | User 58 | .Field('id', Int(Id, Default('autoincrement()'), Map('_id'), Raw("@db.Value('foo')"))) 59 | .Field('email', String(Unique, db.VarChar(4))) 60 | .Field('name', String(Nullable)) 61 | .Field('height', Float(Default(1.80)), "The user model") 62 | .Field('role', Role('USER', Nullable)) 63 | .Field('foo', Foo()) // no-default non-nullable enum 64 | .Field('bar', Foo(Nullable)) 65 | .Relation('posts', OneToMany(Post, "WrittenPosts"), "Relations are cool") 66 | .Relation('pinned', OneToOne(Post, "PinnedPost", Nullable)) 67 | .Mixin(Timestamps); 68 | 69 | // prettier-ignore 70 | Post 71 | .Field('id', Int(Id, Default('autoincrement()'), db.UnsignedSmallInt)) 72 | .Field('published', Boolean(Default(false) )) 73 | .Field('title', String(Limit(255))) 74 | .Relation( 75 | 'author', 76 | ManyToOne( 77 | User, 78 | 'WrittenPosts', 79 | Fields('authorId', Int(Nullable)), 80 | References('id'), 81 | OnUpdate('Restrict'), 82 | OnDelete('SetNull'), 83 | Nullable, 84 | ), 85 | ) 86 | .Field('pinnedById', Int(Nullable)) 87 | .Relation( 88 | 'pinnedBy', 89 | OneToOne( 90 | User, 91 | 'PinnedPost', 92 | Fields('pinnedById'), 93 | References('id'), 94 | Nullable, 95 | ), 96 | ) 97 | .Relation('stars', OneToMany(Star)) 98 | .Mixin(Timestamps) 99 | .Raw(`@@map("comments")`); 100 | 101 | // prettier-ignore 102 | Star 103 | .Field('id', Int(Id, Default('autoincrement()'))) 104 | .Field('decimal', Decimal(db.Decimal(10, 20))) 105 | .Field('postId', Int(Nullable)) 106 | .Relation('post', ManyToOne(Post, Fields('postId'), References('id'))) 107 | .Mixin(Timestamps) 108 | .Field("location", Unsupported("polygon", Nullable)) 109 | .Block(Compound.Unique(["A", "B"], Map("_AB_unique"))) 110 | .Block(Compound.Index(["wow"], Map("_B_index")), "Block level comments?") 111 | .Block(Compound.Map("Group")) 112 | .Block(Compound.Fulltext(["location", "decimal"])) 113 | 114 | export default [Role, User, Post, Star, Foo]; 115 | 116 | // let x = OneToOne(Post, 'WrittenPosts', Fields('wow'), References('wee')); 117 | // let a = OneToOne(Post, Fields('bestPostId'), References('id')); // good 118 | // let b = OneToOne(Post, References('id'), Fields('bestPostId')); // bad 119 | // let c = OneToOne(Post, Fields('bestPostId')); // bad 120 | // let d = OneToOne(Post); // good 121 | -------------------------------------------------------------------------------- /src/public/fields/relations.ts: -------------------------------------------------------------------------------- 1 | import * as Types from '../../types'; 2 | import { Reference } from '../../types'; 3 | import { ReferentialAction, Relation } from '../../types/fields'; 4 | import { isString, nonNullable } from '../../types/utils'; 5 | import { Int, String } from './scalars'; 6 | 7 | // @relation("name", fields:[foo], references: ["bar"]) 8 | type OptionallyWithName[]> = 9 | | [name: string, ...rest: M] 10 | | M; 11 | 12 | export const OneToMany = ( 13 | model: M, 14 | ...modifiers: OptionallyWithName<'OneToMany', Types.Modifier<'OneToMany'>[]> 15 | ) => 16 | ({ 17 | type: 'OneToMany' as const, 18 | modifiers: [ 19 | { type: 'model', value: model }, 20 | ...(isString(modifiers[0]) 21 | ? [{ type: 'name', value: modifiers[0] }, ...modifiers.slice(1)] 22 | : modifiers), 23 | ], 24 | } as Types.Fields.Field<'OneToMany'>); 25 | 26 | export const ManyToOne = < 27 | T extends 'ManyToOne', 28 | M extends Types.Blocks.Model, 29 | K extends Types.Modifiers<'ManyToOne'>, 30 | >( 31 | model: M, 32 | ...modifiers: OptionallyWithName< 33 | 'ManyToOne', 34 | [ 35 | fields: Types.Modifier<'ManyToOne', 'fields'>, 36 | references: Types.Modifier<'ManyToOne', 'references'>, 37 | ...modifiers: Types.Modifier< 38 | 'ManyToOne', 39 | Exclude 40 | >[], 41 | ] 42 | > 43 | ): Types.Fields.Field => ({ 44 | type: 'ManyToOne' as const as T, 45 | modifiers: [ 46 | { 47 | type: 'model' as const, 48 | value: model, 49 | }, 50 | ...(isString(modifiers[0]) 51 | ? [{ type: 'name', value: modifiers[0] }, ...modifiers.slice(1)] 52 | : modifiers), 53 | ].filter(nonNullable) as Types.Modifier[], 54 | }); 55 | 56 | export const OneToOne = < 57 | T extends 'OneToOne', 58 | M extends Types.Blocks.Model, 59 | K extends Types.Modifiers<'OneToOne'>, 60 | >( 61 | model: M, 62 | ...modifiers: 63 | | OptionallyWithName< 64 | 'OneToOne', 65 | [ 66 | fields: Types.Modifier<'OneToOne', 'fields'>, 67 | references: Types.Modifier<'OneToOne', 'references'>, 68 | ...modifiers: Types.Modifier< 69 | 'OneToOne', 70 | Exclude 71 | >[], 72 | ] 73 | > 74 | | OptionallyWithName< 75 | T, 76 | Types.Modifier>[] 77 | > 78 | ): Types.Fields.Field => ({ 79 | type: 'OneToOne' as const as T, 80 | modifiers: [ 81 | { 82 | type: 'model' as const, 83 | value: model, 84 | }, 85 | ...(isString(modifiers[0]) 86 | ? [{ type: 'name', value: modifiers[0] }, ...modifiers.slice(1)] 87 | : modifiers), 88 | ].filter(nonNullable) as Types.Modifier[], 89 | }); 90 | 91 | export const Fields = ( 92 | ...fields: 93 | | string[] 94 | | [ 95 | reference: string, 96 | scalar: Types.Fields.Field<'Int'> | Types.Fields.Field<'String'>, 97 | ] 98 | ): Types.Modifier => ({ 99 | type: 'fields' as const, 100 | value: fields, 101 | }); 102 | 103 | export const References = ( 104 | ...references: string[] 105 | ): Types.Modifier => ({ 106 | type: 'references' as const, 107 | value: references, 108 | }); 109 | 110 | export const OnUpdate = ( 111 | referentialAction: ReferentialAction, 112 | ): Types.Modifier => ({ 113 | type: 'onUpdate' as const, 114 | value: referentialAction, 115 | }); 116 | 117 | export const OnDelete = ( 118 | referentialAction: ReferentialAction, 119 | ): Types.Modifier => ({ 120 | type: 'onDelete' as const, 121 | value: referentialAction, 122 | }); 123 | -------------------------------------------------------------------------------- /src/public/fields/enums.ts: -------------------------------------------------------------------------------- 1 | import * as Types from '../../types'; 2 | import { isString, nonNullable } from '../../types/utils'; 3 | 4 | export const Key = ( 5 | ...args: 6 | | [name: T, ...modifiers: Types.Modifier<'EnumKey'>[]] 7 | | [name: T, ...modifiers: Types.Modifier<'EnumKey'>[], comment: string] 8 | ): Types.Fields.EnumKey => { 9 | const [name, ...modifiers] = args; 10 | 11 | // condition is true for when name & comment, without len check would always insert 12 | // a comment with the name of the key, e.g. 13 | // enum Foo { 14 | // // Bar 15 | // Bar 16 | // } 17 | return args.length >= 2 && isString(args[args.length - 1]) 18 | ? { 19 | name, 20 | modifiers: [ 21 | ...(modifiers.slice( 22 | 0, 23 | modifiers.length - 1, 24 | ) as unknown as Types.Modifier<'EnumKey'>[]), 25 | { type: 'comment' as const, value: args[args.length - 1] as string }, 26 | ], 27 | } 28 | : { name, modifiers: modifiers as Types.Modifier<'EnumKey'>[] }; 29 | }; 30 | 31 | class $Enum 32 | extends Function 33 | implements Types.Blocks.Block<'enum'> 34 | { 35 | type: 'enum' = 'enum' as const; 36 | columns: Types.Column<'EnumKey' | 'Comment'>[]; 37 | 38 | constructor(public name: string, comment: string | null, keys: K) { 39 | super(); 40 | 41 | // Define the keys of the enum 42 | this.columns = keys.map( 43 | k => 44 | ({ 45 | name: k.name, 46 | type: 'EnumKey' as const, 47 | modifiers: k.modifiers, 48 | } as Types.Column<'EnumKey' | 'Comment'>), 49 | ); 50 | 51 | if (comment) { 52 | this.columns.unshift({ 53 | name: 'comment', 54 | type: 'Comment' as const, 55 | modifiers: [{ type: 'value', value: comment }], 56 | } as Types.Column<'EnumKey' | 'Comment'>); 57 | } 58 | 59 | // evil object reference proxy hacking _call overrides gives us nice curried classes 60 | return new Proxy(this, { 61 | apply: ( 62 | target, 63 | _, 64 | args: [K[number] | Types.Modifier<'Enum'>, ...Types.Modifier<'Enum'>[]], 65 | ) => target._call(...(args as any)), 66 | }); 67 | } 68 | 69 | _call(...modifiers: Types.Modifier<'Enum'>[]): Types.Fields.Field<'Enum'>; 70 | _call( 71 | initial: K[number] | Types.Modifier<'Enum'>, 72 | ...modifiers: Types.Modifier<'Enum'>[] 73 | ): Types.Fields.Field<'Enum'> { 74 | return { 75 | type: 'Enum' as const, 76 | modifiers: [ 77 | { type: 'enum' as const, value: this.name }, 78 | ...[ 79 | typeof initial == 'string' 80 | ? { 81 | type: 'default', 82 | value: initial, 83 | } 84 | : (initial as Types.Modifier<'Enum'>), 85 | ...modifiers, 86 | ], 87 | ].filter( 88 | (v, i, a) => nonNullable(v) && a.findIndex(m => m.type == v.type) === i, 89 | ) as Types.Modifier<'Enum'>[], 90 | }; 91 | } 92 | } 93 | 94 | // return type _call signature 95 | type R = (>( 96 | initial?: E[number]['name'] | Types.Modifier<'Enum', M>, 97 | ...modifiers: Types.Modifier<'Enum', M>[] 98 | ) => Types.Fields.Field<'Enum', M>) & 99 | Types.Blocks.Enum; 100 | 101 | export function Enum( 102 | name: string, 103 | ...keys: E 104 | ): R; 105 | export function Enum( 106 | name: string, 107 | comment: string, 108 | ...keys: E 109 | ): R; 110 | export function Enum( 111 | name: string, 112 | ...args: [string, ...E] | E 113 | ): R { 114 | const [comment, ...keys] = args; 115 | return new $Enum( 116 | name, 117 | typeof comment == 'string' ? comment : null, 118 | typeof comment == 'string' ? (keys as E) : ([comment, ...keys] as E), 119 | ) as any; // _call 120 | } 121 | -------------------------------------------------------------------------------- /src/__tests__/__snapshots__/index.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` 1`] = `" test Example"`; 4 | 5 | exports[` 2`] = `" test Example?"`; 6 | 7 | exports[` 3`] = `" test Example @default(Foo)"`; 8 | 9 | exports[` 4`] = `" test Example? @default(Foo)"`; 10 | 11 | exports[`refract enum block generation should generate an enum 1`] = ` 12 | "enum Example { 13 | Qux 14 | // This is a comment 15 | Foo 16 | Bar @map(\\"Baz\\") 17 | }" 18 | `; 19 | 20 | exports[`refract enum block generation should generate an enum with a comment 1`] = ` 21 | "// An Enum with a comment 22 | enum Example { 23 | Qux 24 | // This is a comment 25 | Foo 26 | Bar @map(\\"Baz\\") 27 | }" 28 | `; 29 | 30 | exports[`refract should generate the schema 1`] = ` 31 | "// refract https://github.com/cwqt/refract - generated in x ms ----------------- 32 | // datasource ---------------------------------------------------------------------- 33 | 34 | datasource db { 35 | url = env(\\"DATABASE_URL\\") 36 | provider = \\"mysql\\" 37 | shadowDatabaseUrl = env(\\"DATABASE_SHADOW_URL\\") 38 | referentialIntegrity = \\"prisma\\" 39 | } 40 | 41 | // generators ---------------------------------------------------------------------- 42 | 43 | generator client { 44 | provider = \\"prisma-client-js\\" 45 | binaryTargets = [\\"native\\",\\"rhel-openssl-1.0.x\\",\\"linux-arm64-openssl-1.0.x\\",\\"darwin-arm64\\"] 46 | previewFeatures = [\\"referentialIntegrity\\"] 47 | } 48 | 49 | // enums --------------------------------------------------------------------------- 50 | 51 | // This is the Role Enum 52 | enum Role { 53 | // This is the admin role 54 | ADMIN @map(\\"admin\\") 55 | USER @map(\\"user\\") 56 | // This is the owner role 57 | OWNER @map(\\"owner\\") 58 | } 59 | 60 | enum Foo { 61 | Bar 62 | Baz 63 | } 64 | 65 | // models -------------------------------------------------------------------------- 66 | 67 | // This is the User model 68 | model User { 69 | id Int @id @default(autoincrement()) @map(\\"_id\\") @db.Value('foo') 70 | email String @unique @db.VarChar(4) 71 | name String? 72 | // The user model 73 | height Float @default(1.8) 74 | role Role? @default(USER) 75 | foo Foo 76 | bar Foo? 77 | // Relations are cool 78 | posts Post[] @relation(\\"WrittenPosts\\") 79 | pinned Post? @relation(\\"PinnedPost\\") 80 | createdAt DateTime @default(now()) 81 | updatedAt DateTime @updatedAt @db.Date(6) 82 | @@index([mixin, index]) 83 | } 84 | 85 | model Post { 86 | id Int @id @default(autoincrement()) @db.UnsignedSmallInt 87 | published Boolean @default(false) 88 | title String 89 | authorId Int? 90 | author User? @relation(\\"WrittenPosts\\", fields: [authorId], references: [id], onUpdate: Restrict, onDelete: SetNull) 91 | pinnedById Int? 92 | pinnedBy User? @relation(\\"PinnedPost\\", fields: [pinnedById], references: [id]) 93 | stars Star[] 94 | createdAt DateTime @default(now()) 95 | updatedAt DateTime @updatedAt @db.Date(6) 96 | @@index([mixin, index]) 97 | @@map(\\"comments\\") 98 | } 99 | 100 | model Star { 101 | id Int @id @default(autoincrement()) 102 | decimal Decimal @db.Decimal(10, 20) 103 | postId Int? 104 | post Post @relation(fields: [postId], references: [id]) 105 | createdAt DateTime @default(now()) 106 | updatedAt DateTime @updatedAt @db.Date(6) 107 | @@index([mixin, index]) 108 | location Unsupported(\\"polygon\\")? 109 | @@unique([A, B], map: \\"_AB_unique\\") 110 | // Block level comments? 111 | @@index([wow], map: \\"_B_index\\") 112 | @@map(\\"Group\\") 113 | @@fulltext([location, decimal]) 114 | }" 115 | `; 116 | -------------------------------------------------------------------------------- /src/codegen/lib/pipe.ts: -------------------------------------------------------------------------------- 1 | // Nabbed from: https://github.com/gcanti/fp-ts/blob/62984a0920587a4deb5e5da8d98ec276fb53bb41/src/function.ts#L129 2 | 3 | /** 4 | * Performs left-to-right function composition. The first argument may have any arity, the remaining arguments must be unary. 5 | * 6 | * See also [`pipe`](#pipe). 7 | * 8 | * @example 9 | * import { pipe } from 'fp-ts/function' 10 | * 11 | * const len = (s: string): number => s.length 12 | * const double = (n: number): number => n * 2 13 | * 14 | * const f = pipe(len, double) 15 | * 16 | * assert.strictEqual(f('aaa'), 6) 17 | * 18 | * @since 2.0.0 19 | */ 20 | export function pipe, B>( 21 | ab: (...a: A) => B, 22 | ): (...a: A) => B; 23 | export function pipe, B, C>( 24 | ab: (...a: A) => B, 25 | bc: (b: B) => C, 26 | ): (...a: A) => C; 27 | export function pipe, B, C, D>( 28 | ab: (...a: A) => B, 29 | bc: (b: B) => C, 30 | cd: (c: C) => D, 31 | ): (...a: A) => D; 32 | export function pipe, B, C, D, E>( 33 | ab: (...a: A) => B, 34 | bc: (b: B) => C, 35 | cd: (c: C) => D, 36 | de: (d: D) => E, 37 | ): (...a: A) => E; 38 | export function pipe, B, C, D, E, F>( 39 | ab: (...a: A) => B, 40 | bc: (b: B) => C, 41 | cd: (c: C) => D, 42 | de: (d: D) => E, 43 | ef: (e: E) => F, 44 | ): (...a: A) => F; 45 | export function pipe, B, C, D, E, F, G>( 46 | ab: (...a: A) => B, 47 | bc: (b: B) => C, 48 | cd: (c: C) => D, 49 | de: (d: D) => E, 50 | ef: (e: E) => F, 51 | fg: (f: F) => G, 52 | ): (...a: A) => G; 53 | export function pipe, B, C, D, E, F, G, H>( 54 | ab: (...a: A) => B, 55 | bc: (b: B) => C, 56 | cd: (c: C) => D, 57 | de: (d: D) => E, 58 | ef: (e: E) => F, 59 | fg: (f: F) => G, 60 | gh: (g: G) => H, 61 | ): (...a: A) => H; 62 | export function pipe, B, C, D, E, F, G, H, I>( 63 | ab: (...a: A) => B, 64 | bc: (b: B) => C, 65 | cd: (c: C) => D, 66 | de: (d: D) => E, 67 | ef: (e: E) => F, 68 | fg: (f: F) => G, 69 | gh: (g: G) => H, 70 | hi: (h: H) => I, 71 | ): (...a: A) => I; 72 | export function pipe< 73 | A extends ReadonlyArray, 74 | B, 75 | C, 76 | D, 77 | E, 78 | F, 79 | G, 80 | H, 81 | I, 82 | J, 83 | >( 84 | ab: (...a: A) => B, 85 | bc: (b: B) => C, 86 | cd: (c: C) => D, 87 | de: (d: D) => E, 88 | ef: (e: E) => F, 89 | fg: (f: F) => G, 90 | gh: (g: G) => H, 91 | hi: (h: H) => I, 92 | ij: (i: I) => J, 93 | ): (...a: A) => J; 94 | export function pipe( 95 | ab: Function, 96 | bc?: Function, 97 | cd?: Function, 98 | de?: Function, 99 | ef?: Function, 100 | fg?: Function, 101 | gh?: Function, 102 | hi?: Function, 103 | ij?: Function, 104 | ): unknown { 105 | switch (arguments.length) { 106 | case 1: 107 | return ab; 108 | case 2: 109 | return function (this: unknown) { 110 | return bc!(ab.apply(this, arguments)); 111 | }; 112 | case 3: 113 | return function (this: unknown) { 114 | return cd!(bc!(ab.apply(this, arguments))); 115 | }; 116 | case 4: 117 | return function (this: unknown) { 118 | return de!(cd!(bc!(ab.apply(this, arguments)))); 119 | }; 120 | case 5: 121 | return function (this: unknown) { 122 | return ef!(de!(cd!(bc!(ab.apply(this, arguments))))); 123 | }; 124 | case 6: 125 | return function (this: unknown) { 126 | return fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))); 127 | }; 128 | case 7: 129 | return function (this: unknown) { 130 | return gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments))))))); 131 | }; 132 | case 8: 133 | return function (this: unknown) { 134 | return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))))); 135 | }; 136 | case 9: 137 | return function (this: unknown) { 138 | return ij!( 139 | hi!(gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))))), 140 | ); 141 | }; 142 | } 143 | return; 144 | } 145 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | # [1.3.11] 4 | 5 | - Better argument names for Decimal types for MySQL 6 | 7 | # [1.3.9] [1.3.10] 8 | 9 | - Expose schema generation without writing via `Refract.generate` 10 | 11 | # [1.3.8] 12 | 13 | - Actually fix Enum fields 14 | 15 | ## [1.3.7] 16 | 17 | - Fixes inability to have non-nullable non-default enum columns 18 | - Fixes issue where enum keys without a comment, would always have a comment 19 | which would be the name of the key itself 20 | 21 | ## [1.3.5] 22 | 23 | - Fixes MySQL native type argument for `Char` 24 | () 25 | 26 | ## [1.3.4] 27 | 28 | - Fixes crash when previewFeatures are not available in generator (https://github.com/cwqt/refract/pull/12) 29 | 30 | ## [1.3.3] 31 | 32 | - Allows `Mixins` to use `.Block()` for `@@index` etc. 33 | 34 | ## [1.3.2] 35 | 36 | - Relationships fields in more type safe and shorter way 37 | () 38 | 39 | ## [1.3.1] 40 | 41 | - Documentation improvements 42 | 43 | ## [1.3.0] 44 | 45 | - Deprecated `Comment` modifier over changing `.Field()` & Enum signatures to 46 | include an optional ending parameter 47 | 48 | ## [1.2.3] 49 | 50 | - Update README image 51 | 52 | ## [1.2.2] 53 | 54 | - Adds `@@fulltext` compound field 55 | 56 | ## [1.2.1] 57 | 58 | - Improved documentation 59 | 60 | ## [1.2.0] 61 | 62 | - Adds ability to add comments to models / enums 63 | - Adds `Comment` modifier 64 | 65 | ## [1.1.4] 66 | 67 | - Refactors and fixes bugs in the postgresql native db modifiers () 68 | - Adds support to CockroachDB native modifiers and scallar array modifier 69 | () 70 | 71 | ## [1.1.3] 72 | 73 | - Fixes nullable enums 74 | 75 | ## [1.1.2] 76 | 77 | - Allows for direct schema imports into `Refract` 78 | - e.g. `import schema from './schema'` 79 | 80 | ## [1.1.1] 81 | 82 | Spoke too soon 83 | 84 | - Adds all the `@db` attributes for `mysql`, `postgresql` & `mongodb` providers 85 | - Adds `.Block()` for properties like `@@map`, `@@id` etc. 86 | - Adds `Unsupported` type 87 | 88 | ## [1.1.0] 89 | 90 | Should be at parity with Prisma schema now 91 | 92 | - Adds `OnUpdate` & `OnDelete` referential action modifiers 93 | - Adds pre-generation checks for relations (assert both sides have Ids etc.) 94 | - Adds support for `name` field to Relation fields for ambigious relations 95 | - Renames `Pk().Fk()` to `Fields` & `References` modifiers 96 | 97 | Once again thanks to [bacali95](https://github.com/bacali95) for contributing! 98 | 99 | ## [1.0.12] 100 | 101 | - Fixes `String` type to be able to have `@id` decorator 102 | - Improved formatting (decorator alignment) 103 | - Fixes transforming function calls as values 104 | 105 | Big thanks to [bacali95](https://github.com/bacali95) for these changes :) 106 | 107 | ## [1.0.11] 108 | 109 | ## [1.0.10] 110 | 111 | - Adds `Raw` decorator escape hatch, similar to `.Raw()` model method 112 | - Can now do `Raw('@db.ObjectId')` etc to use un-supported decorators 113 | - Fixes some out of date documentation 114 | 115 | ## [1.0.9] 116 | 117 | - Adds `Map` decorator (e.g. `@map("foo")`) 118 | - Renames `Varchar` to `String` 119 | - Renames `Index` to `Id` 120 | - Adds `cuid()`, `uuid()` 121 | - Adds `Ignore` decorator (e.g. `@ignore`) 122 | - Adds `Float`, `BigInt`, `Bytes`, `Decimal` scalars 123 | - Refactors how Enums are created 124 | - Adds `Key` 125 | - Enums definitions can now have decorators 126 | - Refactors types on data-types to be more specific 127 | 128 | ## [1.0.8] 129 | 130 | ## [1.0.7] 131 | 132 | ## [1.0.6] 133 | 134 | - Fix issue with `Enum` codegen always being nullable when having >=1 modifier 135 | - Improve documentation 136 | 137 | ## [1.0.5] 138 | 139 | - Useage documentation 140 | - Added CI testing 141 | 142 | ## [1.0.4] 143 | 144 | - Removed field checking on relationships because of fails with circular relationships 145 | 146 | ## [1.0.3] 147 | 148 | - Added block alignment 149 | - Added `OneToOne()` relationships 150 | 151 | ## [1.0.2] 152 | 153 | - Added `.Raw()` Prisma escape hatch 154 | - Added `.Mixin()` utility field 155 | 156 | ## [1.0.1] 157 | 158 | - Added enums 159 | 160 | ## [1.0.0] 161 | 162 | - Initial release 163 | -------------------------------------------------------------------------------- /src/codegen/column.ts: -------------------------------------------------------------------------------- 1 | import { modifier } from './modifiers'; 2 | import * as Types from '../types'; 3 | import { isArray, isString, nonNullable } from '../types/utils'; 4 | 5 | // Converts a Column to a Prisma row string 6 | export const column = (column: Types.Column): string => { 7 | if (Types.Fields.isUnsupported(column)) return unsupported(column); 8 | if (Types.Fields.isCompound(column)) return compound(column); 9 | if (Types.Fields.isComment(column)) 10 | return `\t// ${column.modifiers[0].value}`; 11 | if (Types.Fields.isRaw(column)) return `\t${column.modifiers[0].value}`; 12 | if (Types.Fields.isEnum(column)) return enumeration(column); 13 | if (Types.Fields.isEnumKey(column)) return enumKey(column); 14 | if (Types.Fields.isScalar(column)) return scalar(column); 15 | if (Types.Fields.isRelation(column)) return relationship(column); 16 | 17 | throw new Error( 18 | `CodegenError: Couldn't figure out type for column: ${column.name}`, 19 | ); 20 | }; 21 | 22 | const unsupported = (column: Types.Column<'Unsupported'>): string => { 23 | const isNullable = column.modifiers.find(({ type }) => type == 'nullable'); 24 | 25 | return `\t${column.name} Unsupported${modifier( 26 | column.type, 27 | column.modifiers[0], 28 | )}${isNullable ? '?' : ''}`; 29 | }; 30 | 31 | // enum { Foo Bar } 32 | const enumKey = (column: Types.Column<'EnumKey'>) => 33 | `\t${column.name} ${column.modifiers 34 | .map(m => modifier<'EnumKey'>(column.type, m)) 35 | .join(' ')}`.trimEnd(); 36 | 37 | export const enumeration = (column: Types.Column<'Enum'>) => { 38 | const [type, ...modifiers] = column.modifiers; 39 | const isNullable = modifiers.find(({ type }) => type == 'nullable'); 40 | 41 | return `\t${column.name} ${type.value}${isNullable ? '?' : ''} ${modifiers 42 | .map(m => modifier(column.type, m)) 43 | .join(' ')}`.trimEnd(); 44 | }; 45 | 46 | const scalar = (column: Types.Column) => { 47 | const isNullable = column.modifiers.find(({ type }) => type == 'nullable'); 48 | const isArray = column.modifiers.find(({ type }) => type == 'array'); 49 | 50 | return `\t${column.name} ${column.type}${isArray ? '[]' : ''}${ 51 | isNullable ? '?' : '' 52 | } ${column.modifiers.map(m => modifier(column.type, m)).join(' ')}`.trimEnd(); 53 | }; 54 | 55 | const compound = (column: Types.Column) => { 56 | if (column.type == '@@ignore') return `\t${column.type}`; 57 | if (column.type == '@@map') 58 | return `\t${column.type}(${`"${column.modifiers[0].value}"`})`; 59 | 60 | const map = column.modifiers.find(v => (v.type as 'values' | 'map') == 'map'); 61 | const args = [ 62 | `[${(column.modifiers[0].value as string[]).join(', ')}]`, 63 | map ? `map: "${map.value}"` : null, 64 | ].filter(nonNullable); 65 | 66 | return `\t${column.type}(${args.join(', ')})`; 67 | }; 68 | 69 | const relationship = (column: Types.Column) => { 70 | if (column.type == 'OneToOne' || column.type == 'ManyToOne') { 71 | const modifiers = column.modifiers as Types.Modifier< 72 | 'OneToOne' | 'ManyToOne' 73 | >[]; 74 | const isNullable = modifiers.find(({ type }) => type === 'nullable'); 75 | 76 | const [model, ...restModifiers] = modifiers.filter( 77 | ({ type }) => type !== 'nullable', 78 | ) as [ 79 | Types.Modifier<'OneToOne' | 'ManyToOne', 'model'>, 80 | ...Types.Modifier< 81 | 'OneToOne' | 'ManyToOne', 82 | 'name' | 'fields' | 'references' | 'onUpdate' | 'onDelete' 83 | >[], 84 | ]; 85 | 86 | const relationModifier = restModifiers.length 87 | ? `@relation(${restModifiers 88 | .sort(({ type }) => (type === 'name' ? -1 : 0)) 89 | .map(({ type, value }) => 90 | type === 'name' 91 | ? `"${value}"` 92 | : `${type}: ${isArray(value) ? `[${value.join(', ')}]` : value}`, 93 | ) 94 | .join(', ')})` 95 | : ''; 96 | 97 | return `\t${column.name} ${ 98 | isString(model.value) ? model.value : model.value.name 99 | }${isNullable ? '?' : ''} ${relationModifier}`.trimEnd(); 100 | } 101 | 102 | if (column.type == 'OneToMany') { 103 | const [model, relationName] = column.modifiers as unknown as [ 104 | Types.Modifier<'OneToMany', 'model'>, 105 | Types.Modifier<'OneToMany', 'name'>, 106 | ]; 107 | 108 | const relationModifier = relationName 109 | ? `@relation("${relationName.value}")` 110 | : ''; 111 | 112 | return `\t${column.name} ${ 113 | isString(model.value) ? model.value : model.value.name 114 | }[] ${relationModifier}`.trimEnd(); 115 | } 116 | }; 117 | -------------------------------------------------------------------------------- /src/codegen/validate.ts: -------------------------------------------------------------------------------- 1 | import { DbModifier } from '../public/db/utils'; 2 | import * as Types from '../types'; 3 | import { Config, Provider } from '../types'; 4 | import { isRelation, Relation, isScalar, isDbModifier } from '../types/fields'; 5 | 6 | export const validateModel = 7 | (config: Config) => 8 | (model: Types.Blocks.Model): Types.Blocks.Model => { 9 | // Check not using mysql db with mongo @db modifiers etc. 10 | for (const field of model.columns.filter(isScalar)) { 11 | const mismatches = field.modifiers 12 | .filter(isDbModifier) 13 | .map(c => c as any as DbModifier) 14 | .filter(v => !v.type.includes(config.datasource.provider)); 15 | 16 | if (mismatches.length) { 17 | throw new Error( 18 | `ModifierErr: Provider is "${config.datasource.provider}", but ${model.name} is using a non-${config.datasource.provider} @db modifier`, 19 | ); 20 | } 21 | 22 | const isArray = field.modifiers.some(m => m.type === 'array'); 23 | if ( 24 | isArray && 25 | !['postgresql', 'cockroachdb'].includes(config.datasource.provider) 26 | ) { 27 | throw new Error( 28 | `ModifierErr: Scalar lists are only supported when using PostgreSQL or CockroachDB.`, 29 | ); 30 | } 31 | 32 | const isNullable = field.modifiers.some(m => m.type === 'nullable'); 33 | if (isArray && isNullable) { 34 | throw new Error( 35 | `ModifierErr: Field '${field.name}' cannot be an array and optional in the same time`, 36 | ); 37 | } 38 | } 39 | 40 | for (const relation of model.columns.filter(isRelation)) { 41 | const modifiers = relation.modifiers as Types.Modifier[]; 42 | const { value: otherSideModel } = modifiers[0] as Types.Modifier< 43 | Relation, 44 | 'model' 45 | >; 46 | 47 | const relationName = modifiers.find( 48 | ({ type }) => type === 'name', 49 | ) as Types.Modifier; 50 | 51 | if (relationName) { 52 | const otherSideRelation = otherSideModel.columns 53 | .filter(isRelation) 54 | .find(r => 55 | r.modifiers.some( 56 | ({ type, value }) => 57 | type === 'name' && value === relationName.value, 58 | ), 59 | ); 60 | 61 | if (!otherSideRelation) 62 | throw new Error( 63 | `RelationshipErr: The other side of the relation '${relation.name}' with name '${relationName.value}' don't exist in model '${model.name}'`, 64 | ); 65 | } 66 | 67 | if (model.name === otherSideModel.name && !relationName) 68 | throw new Error( 69 | `RelationshipErr: The model '${model.name}' have an ambiguous self relation. The fields '${relation.name}' and '${otherSideModel.name}' both refer to '${model.name}'. If they are part of the same relation add the same relation name for them with RelationName() modifier`, 70 | ); 71 | 72 | if (relation.type !== 'OneToOne' && relation.type !== 'ManyToOne') 73 | continue; 74 | 75 | const castedModifiers = modifiers as Types.Modifier< 76 | 'OneToOne' | 'ManyToOne' 77 | >[]; 78 | 79 | const fields = castedModifiers.find( 80 | ({ type }) => type === 'fields', 81 | ) as Types.Modifier<'OneToOne' | 'ManyToOne', 'fields'>; 82 | 83 | if (fields) { 84 | const missingFields = fields.value.filter( 85 | f => !model.columns.some(c => c.name === f), 86 | ); 87 | 88 | if (missingFields.length) 89 | throw new Error( 90 | `RelationshipErr: Columns in 'fields' don't exist in model '${ 91 | model.name 92 | }': ${missingFields.map(m => `'${m}'`).join(', ')}`, 93 | ); 94 | } 95 | 96 | const references = castedModifiers.find( 97 | ({ type }) => type === 'references', 98 | ) as Types.Modifier<'OneToOne' | 'ManyToOne', 'references'>; 99 | 100 | if (references) { 101 | const missingReferences = references.value.filter( 102 | f => !otherSideModel.columns.some(c => c.name === f), 103 | ); 104 | 105 | if (missingReferences.length) 106 | throw new Error( 107 | `RelationshipErr: Referenced columns in 'references' don't exist in model '${ 108 | otherSideModel.name 109 | }': ${missingReferences.map(m => `'${m}'`).join(', ')}`, 110 | ); 111 | } 112 | 113 | if (fields && references) { 114 | if (fields.value.length !== references.value.length) 115 | throw new Error( 116 | `RelationshipErr: You must specify the same number of fields in 'fields' and 'references' for relation '${relation.name}' in model '${model.name}'`, 117 | ); 118 | 119 | for (let i = 0; i < fields.value.length; i++) { 120 | const field = fields.value[i]; 121 | const reference = references.value[i]; 122 | 123 | const column = model.columns.find(c => c.name === field)!; 124 | const otherSideColumn = otherSideModel.columns.find( 125 | c => c.name === reference, 126 | )!; 127 | 128 | if (column.type !== otherSideColumn.type) 129 | throw new Error( 130 | `RelationshipErr: The type of the field '${field}' in the model '${model.name}' does not match the type of the referenced field '${reference}' in model '${otherSideModel.name}'`, 131 | ); 132 | } 133 | } 134 | 135 | const missingAttribute = 136 | fields && !references 137 | ? 'references' 138 | : !fields && references 139 | ? 'fields' 140 | : ''; 141 | 142 | if (missingAttribute) 143 | throw new Error( 144 | `RelationshipErr: Relation '${relation.name}' is missing the '${missingAttribute}' attribute`, 145 | ); 146 | 147 | if (relation.type === 'ManyToOne' && !fields && !references) 148 | throw new Error( 149 | `RelationshipErr: Relation many-to-one '${relation.name}' is missing the 'fields' and 'references' attributes`, 150 | ); 151 | 152 | const isNullable = castedModifiers.find( 153 | ({ type }) => type === 'nullable', 154 | ) as Types.Modifier<'OneToOne' | 'ManyToOne', 'nullable'>; 155 | 156 | if (relation.type === 'OneToOne' && !isNullable && !fields && !references) 157 | throw new Error( 158 | `RelationshipErr: The side of the one-to-one relation without a relation scalar must be optional\n(Model '${otherSideModel.name}', relation '${relation.name}')`, 159 | ); 160 | } 161 | 162 | return model; 163 | }; 164 | -------------------------------------------------------------------------------- /src/__tests__/index.spec.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Array, 3 | Default, 4 | Fields, 5 | Id, 6 | Int, 7 | ManyToOne, 8 | Map, 9 | Model, 10 | Nullable, 11 | OneToMany, 12 | OneToOne, 13 | References, 14 | String, 15 | } from '../'; 16 | import codegen from '../codegen'; 17 | import { enumeration } from '../codegen/enum'; 18 | import { enumeration as enumerationColumn } from '../codegen/column'; 19 | import { Enum, Key } from '../public/fields/enums'; 20 | import * as Types from '../types'; 21 | import schema from './schema'; 22 | 23 | const generate = ( 24 | schema: Types.Config['schema'], 25 | overrides: Partial = {}, 26 | ) => 27 | codegen({ 28 | schema, 29 | datasource: { 30 | url: 'env("DATABASE_URL")', 31 | provider: 'mysql', 32 | shadowDatabaseUrl: 'env("DATABASE_SHADOW_URL")', 33 | referentialIntegrity: 'prisma', 34 | }, 35 | generators: [ 36 | { 37 | name: 'client', 38 | provider: 'prisma-client-js', 39 | binaryTargets: [ 40 | 'native', 41 | 'rhel-openssl-1.0.x', 42 | 'linux-arm64-openssl-1.0.x', 43 | 'darwin-arm64', 44 | ], 45 | previewFeatures: ['referentialIntegrity'], 46 | }, 47 | ], 48 | ...overrides, 49 | }); 50 | 51 | describe('refract', () => { 52 | it('should generate the schema', () => { 53 | const { schema: prisma } = generate(schema); 54 | 55 | console.log(prisma); 56 | 57 | expect(replaceGeneratedTime(prisma)).toMatchSnapshot(); 58 | }); 59 | 60 | describe('should generate implicit many-to-many schema', () => { 61 | const Post = Model('Post'); 62 | const Category = Model('Category'); 63 | 64 | Post.Field('id', Int(Id, Default('autoincrement()'))).Relation( 65 | 'categories', 66 | OneToMany(Category), 67 | ); 68 | 69 | Category.Field('id', Int(Id, Default('autoincrement()'))).Relation( 70 | 'posts', 71 | OneToMany(Post), 72 | ); 73 | 74 | const implicit = generate([Post, Category]); 75 | console.log(implicit.schema); 76 | }); 77 | 78 | describe('enum block generation', () => { 79 | it('should generate an enum', () => { 80 | const e = enumeration( 81 | Enum( 82 | 'Example', 83 | Key('Qux'), 84 | Key('Foo', 'This is a comment'), 85 | Key('Bar', Map('Baz')), 86 | ), 87 | ); 88 | 89 | expect(e).toMatchSnapshot(); 90 | }); 91 | 92 | it('should generate an enum with a comment', () => { 93 | const e = enumeration( 94 | Enum( 95 | 'Example', 96 | 'An Enum with a comment', 97 | Key('Qux'), 98 | Key('Foo', 'This is a comment'), 99 | Key('Bar', Map('Baz')), 100 | ), 101 | ); 102 | 103 | expect(e).toMatchSnapshot(); 104 | }); 105 | }); 106 | 107 | describe('enum column generation', () => { 108 | const e = Enum('Example', Key('Foo'), Key('Bar')); 109 | 110 | const asColumn = (e: Types.Fields.Field<'Enum'>): Types.Column<'Enum'> => ({ 111 | name: 'test', 112 | ...(e as any), 113 | }); 114 | 115 | const nonNullableNoDefault = e(); 116 | expect(enumerationColumn(asColumn(nonNullableNoDefault))).toMatchSnapshot(); 117 | 118 | const nullableNoDefault = e(Nullable); 119 | expect(enumerationColumn(asColumn(nullableNoDefault))).toMatchSnapshot(); 120 | 121 | const nonNullableDefault = e('Foo'); 122 | expect(enumerationColumn(asColumn(nonNullableDefault))).toMatchSnapshot(); 123 | 124 | const nullableDefault = e('Foo', Nullable); 125 | expect(enumerationColumn(asColumn(nullableDefault))).toMatchSnapshot(); 126 | }); 127 | 128 | describe('should validate the schema and throw error when', () => { 129 | it('the other side of the relation is missing when specifying relation name', () => { 130 | const User = Model('User'); 131 | const Post = Model('Post'); 132 | 133 | User.Field('id', Int()).Relation( 134 | 'posts', 135 | OneToMany(Post, 'WrittenPosts'), 136 | ); 137 | Post.Field('authorId', Int(Nullable)).Relation( 138 | 'author', 139 | ManyToOne(User, Fields('authorId'), References('id'), Nullable), 140 | ); 141 | 142 | expect(() => generate([User, Post])).toThrow( 143 | "RelationshipErr: The other side of the relation 'posts' with name 'WrittenPosts' don't exist in model 'User'", 144 | ); 145 | }); 146 | 147 | it('the model have an ambiguous self relation', () => { 148 | const User = Model('User'); 149 | 150 | User.Relation('friend', OneToOne(User)); 151 | 152 | expect(() => generate([User])).toThrow( 153 | "RelationshipErr: The model 'User' have an ambiguous self relation. The fields 'friend' and 'User' both refer to 'User'. If they are part of the same relation add the same relation name for them with RelationName() modifier", 154 | ); 155 | }); 156 | 157 | it('some of the specified column in the Fields modifier are missing in the model', () => { 158 | const User = Model('User'); 159 | const Post = Model('Post'); 160 | 161 | User.Field('id', Int()); 162 | Post.Relation( 163 | 'author', 164 | ManyToOne(User, Fields('authorId'), References('id'), Nullable), 165 | ); 166 | 167 | expect(() => generate([User, Post])).toThrow( 168 | "RelationshipErr: Columns in 'fields' don't exist in model 'Post': 'authorId'", 169 | ); 170 | }); 171 | 172 | it('some of the specified column in the References modifier are missing in the other side model', () => { 173 | const User = Model('User'); 174 | const Post = Model('Post'); 175 | 176 | Post.Field('authorId', Int()).Relation( 177 | 'author', 178 | ManyToOne(User, Fields('authorId'), References('id'), Nullable), 179 | ); 180 | 181 | expect(() => generate([User, Post])).toThrow( 182 | "RelationshipErr: Referenced columns in 'references' don't exist in model 'User': 'id'", 183 | ); 184 | }); 185 | 186 | it('the number of columns specified in the Fields and References modifiers are not equal', () => { 187 | const User = Model('User'); 188 | const Post = Model('Post'); 189 | 190 | User.Field('id', Int()); 191 | Post.Field('authorId', Int()) 192 | .Field('secondId', Int()) 193 | .Relation( 194 | 'author', 195 | ManyToOne( 196 | User, 197 | Fields('authorId', 'secondId'), 198 | References('id'), 199 | Nullable, 200 | ), 201 | ); 202 | 203 | expect(() => generate([User, Post])).toThrow( 204 | "RelationshipErr: You must specify the same number of fields in 'fields' and 'references' for relation 'author' in model 'Post'", 205 | ); 206 | }); 207 | 208 | it('the types of columns specified in the Fields and References modifiers does not match', () => { 209 | const User = Model('User'); 210 | const Post = Model('Post'); 211 | 212 | User.Field('id', Int()).Field('name', String()); 213 | Post.Field('authorId', Int()) 214 | .Field('authorName', Int()) 215 | .Relation( 216 | 'author', 217 | ManyToOne( 218 | User, 219 | Fields('authorId', 'authorName'), 220 | References('id', 'name'), 221 | Nullable, 222 | ), 223 | ); 224 | 225 | expect(() => generate([User, Post])).toThrow( 226 | "RelationshipErr: The type of the field 'authorName' in the model 'Post' does not match the type of the referenced field 'name' in model 'User'", 227 | ); 228 | }); 229 | 230 | it('there is a one-to-one relation with no scalar and not nullable', () => { 231 | const User = Model('User'); 232 | const Post = Model('Post'); 233 | 234 | User.Field('id', Int()).Relation('pinned', OneToOne(Post)); 235 | Post.Field('pinnedById', Int()).Relation( 236 | 'pinnedBy', 237 | OneToOne(User, Fields('pinnedById'), References('id'), Nullable), 238 | ); 239 | 240 | expect(() => generate([User, Post])).toThrow( 241 | "RelationshipErr: The side of the one-to-one relation without a relation scalar must be optional\n(Model 'Post', relation 'pinned')", 242 | ); 243 | }); 244 | 245 | it('there is a scalar array field and not using the correct datasource', () => { 246 | const User = Model('User'); 247 | 248 | User.Field('id', Int(Array)); 249 | 250 | expect(() => generate([User])).toThrow( 251 | 'ModifierErr: Scalar lists are only supported when using PostgreSQL or CockroachDB.', 252 | ); 253 | }); 254 | 255 | it('there is a scalar optional array field', () => { 256 | const User = Model('User'); 257 | 258 | User.Field('id', Int(Array, Nullable)); 259 | 260 | expect(() => 261 | generate([User], { 262 | datasource: { provider: 'postgresql', url: 'url' }, 263 | }), 264 | ).toThrow( 265 | "ModifierErr: Field 'id' cannot be an array and optional in the same time", 266 | ); 267 | }); 268 | }); 269 | }); 270 | 271 | function replaceGeneratedTime(schema: string): string { 272 | return schema.replace(/generated in [\d.]* ms/, 'generated in x ms'); 273 | } 274 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # refract 2 | 3 | Generate [Prisma](https://www.prisma.io) from TypeScript 4 | 5 |

8 | 9 | ## Installation 10 | 11 | ```shell 12 | npm i -D @cwqt/refract 13 | yarn add -D @cwqt/refract 14 | ``` 15 | 16 | ## Usage 17 | 18 | See [here for a full demo](./DEMO.md). 19 | 20 | - [Models](#model) 21 | - [Scalars](#scalars) 22 | - [`@db` attributes](#--db--attributes) 23 | - [Relationships](#relationships) 24 | - [Examples](#examples) 25 | - [OneToOne](#onetoone) 26 | - [Implicit ManyToMany](#implicit-manytomany) 27 | - [Ambiguous relations](#ambiguous-relations) 28 | - [Referentials Actions](#referentials-actions) 29 | - [Enums](#enums) 30 | - [Blocks](#blocks) 31 | - [Mixins](#mixins) 32 | - [Handling circular relationships](#handling-circular-relationships) 33 | 34 | --- 35 | 36 | Use the `Refract` default export of this package to generate a Prisma file. 37 | 38 | ```typescript 39 | // schema.ts 40 | 41 | // Import the entry-point 42 | import Refract from '@cwqt/refract'; 43 | // Import your custom Models 44 | import { Roles, User, Posts } from './models'; 45 | 46 | Refract({ 47 | // Supply models/enums for generation 48 | schema: [Roles, User, Posts], 49 | // https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#datasource 50 | datasource: { 51 | provider: 'postgresql', 52 | url: 'env("DATABASE_URL")', 53 | shadowDatabaseUrl: 'env("DATABASE_SHADOW_URL")', 54 | referentialIntegrity: 'prisma', 55 | }, 56 | // https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#generator 57 | generators: [ 58 | { 59 | provider: 'prisma-client-js', 60 | previewFeatures: ['referentialIntegrity'], 61 | engineType: 'library', 62 | binaryTargets: ['native'], 63 | }, 64 | ], 65 | // Define output path for generated Prisma file 66 | output: path.join(process.cwd(), 'schema.prisma'), 67 | }); 68 | ``` 69 | 70 | A command like `npx ts-node schema.ts` will run this TypeScript code & generate 71 | the resulting Prisma file at the `output` path. 72 | 73 | # Models 74 | 75 | ```typescript 76 | const User = Model('User', 'This is an optional comment'); 77 | 78 | User.Field('id', Int(Id, Default('autoincrement()')), 'The primary key'); 79 | 80 | // // This is an optional comment 81 | // model User { 82 | // // The primary key 83 | // id Int @id @default(autoincrement()) 84 | // } 85 | ``` 86 | 87 | `Model` uses a fluid interface, so you can chain the following methods: 88 | 89 | - `.Field(name, scalar)`: Add a scalar column to a Model 90 | - `.Relation(name, relation)`: Add a relationship to a Model 91 | - `.Block(compound)`: Add a block field, e.g. `@@id`, `@@unique`, `@@map` 92 | - `.Mixin(mixin)`: Inherit columns from a Mixin for compositional Models 93 | - `.Raw(value)`: Escape hatch into writing raw Prisma 94 | 95 | # Scalars 96 | 97 | Scalars are the types of data that the column contains, `Int`, `String` 98 | etc. You can define & re-use Scalars wherever in your models 99 | 100 | ```typescript 101 | const PrimaryKey = Int(Id, Default('autoincrement()')); 102 | 103 | // id Int @id @default("autoincrement()") 104 | m.Field('id', PrimaryKey); 105 | ``` 106 | 107 | ## Modifiers 108 | 109 | Modifiers are functions/objects that append attributes to a column e.g. 110 | 111 | ```typescript 112 | // String? @default("Hello World") 113 | String(Default('Hello World'), Nullable); 114 | 115 | // Int @id @unique @default(autoincrement()) 116 | Int(Id, Unique, Default('autoincrement()')); 117 | 118 | // DateTime @default(now()) @updatedAt 119 | DateTime(Default('now()'), UpdatedAt); 120 | ``` 121 | 122 | Certain modifiers are constrained to certain scalars, the mapping is: 123 | 124 | - `String`: Unique, Id, Default(string | 'auto()'), Limit(number) 125 | - `Int`: Unique, Id, Default('cuid' | 'autoincrement()' | 'uuid()' | number) 126 | - `Float`: Unique, Default(number) 127 | - `BigInt`: Unique, Default(BigInt) 128 | - `Bytes`: Unique 129 | - `Decimal`: Unique 130 | - `Boolean`: Unique 131 | - `DateTime`: Default('now()'), UpdatedAt 132 | - `Unsupported` 133 | 134 | Additionally all scalars can use: Nullable, Map, Ignore, Raw & Array modifiers. 135 | 136 | The `Raw()` modifier can be used as an escape hatch: 137 | 138 | ```typescript 139 | // String @db.ObjectId 140 | String(Raw('@db.ObjectId')); 141 | ``` 142 | 143 | ## `@db` attributes 144 | 145 | Currently there's support for `mysql`, `postgresql`, `cockroachdb` & `mongodb` `@db` 146 | attributes, and can be used like all the other modifiers. 147 | 148 | ```typescript 149 | import { MySql as db } from '@cwqt/refract'; 150 | 151 | // email String @db.VarChar(255) 152 | m.Field('email', String(db.VarChar(255))); 153 | ``` 154 | 155 | Check `src/public/db/mysql.ts` (`mongo.ts`/`postgresql.ts`/`cockroach.ts`) for list of mappings between scalar types & 156 | attributes. 157 | 158 | # Relationships 159 | 160 | - `OneToMany` (model, name?, ...modifiers) 161 | - Nullable 162 | - `OneToOne` (model, name?, fields, references, ...modifiers) 163 | - `OneToOne` (model, name?, ...modifiers) 164 | - Nullable, OnUpdate(Action), OnDelete(Action) 165 | - `ManyToOne` (model, name?, fields, references, ...modifiers) 166 | - Nullable, OnUpdate(Action), OnDelete(Action) 167 | 168 | Where `Action` is one of: `Cascade`, `Restrict`, `NoAction`, `SetNull`, `SetDefault` 169 | 170 | ## Examples 171 | 172 | ### OneToOne 173 | 174 | 175 | ```typescript 176 | const User = Model('User'); 177 | const Something = Model('Something'); 178 | 179 | Something 180 | .Field('id', PrimaryKey) 181 | // Holds foreign key 182 | .Field('userId', Int()) 183 | .Relation('user', OneToOne(User, Fields('userId'), References('id'))); 184 | // Alternatively you can do Fields('userId', Int()) to avoid the extra 185 | // .Field() call, this'll add the column to the model for you 186 | 187 | User 188 | .Field('id', PrimaryKey) 189 | .Relation('thingy', OneToOne(Something)); 190 | ``` 191 | 192 | ### Implicit ManyToMany 193 | 194 | 195 | 196 | 197 | ```typescript 198 | const Post = Model('Post'); 199 | const Category = Model('Category'); 200 | 201 | Post 202 | .Field('id', Int(Id, Default('autoincrement()'))) 203 | .Relation('categories', OneToMany(Category)); 204 | 205 | Category 206 | .Field('id', Int(Id, Default('autoincrement()'))) 207 | .Relation('posts', OneToMany(Post)); 208 | ``` 209 | 210 | ### [Ambiguous relations](https://www.prisma.io/docs/concepts/components/prisma-schema/relations#disambiguating-relations) 211 | 212 | The 2nd parameter of the Relation can be a string & explicitly denote the name 213 | of the relation. 214 | 215 | ```typescript 216 | // pinnedBy User? @relation(name: "PinnedPost", fields: [pinnedById], references: [id]) 217 | m.Relation( 218 | 'pinnedBy', 219 | OneToOne( 220 | User, 221 | 'PinnedPost', 222 | Fields('pinnedById'), 223 | References('id'), 224 | Nullable, 225 | ), 226 | ); 227 | ``` 228 | 229 | ### Referentials Actions 230 | 231 | `OnUpdate` & `OnDelete` modifiers can be used as follows: 232 | 233 | ```typescript 234 | // tag Tag? @relation(fields: [tagId], references: [id], onUpdate: Cascade, onDelete: Cascade) 235 | m.Relation( 236 | 'tag', 237 | ManyToOne( 238 | Fields('tagId'), 239 | References('id'), 240 | OnUpdate('Cascade'), 241 | OnDelete('Cascade'), 242 | Nullable, 243 | ), 244 | ); 245 | ``` 246 | 247 | # Enums 248 | 249 | Composed of two parts: 250 | 251 | - `Enum(name, comment?, ...Key)` 252 | - `Key(value, ...modifiers, comment?)` 253 | - Map 254 | 255 | 256 | ```typescript 257 | const Animal = Enum( 258 | 'Animal', 259 | Key('Seacow'), 260 | Key('Capybara'), 261 | Key('Otter', Map('otter')), 262 | ); 263 | 264 | // fave Animal @default(Seacow) 265 | // null Animal? 266 | model 267 | .Field('fave', Animal('Seacow')) 268 | .Field('null', Animal()); 269 | 270 | const WithComment = Enum( 271 | "Foo", "This is with a comment", 272 | Key("Bar", "Another comment") 273 | ); 274 | // // This is with a comment 275 | // enum Foo { 276 | // // Another comment 277 | // Bar 278 | // } 279 | ``` 280 | 281 | # Blocks 282 | 283 | Used for adding fields like `@@map`, `@@id`, `@@fulltext` etc. 284 | 285 | ```typescript 286 | import { Compound, Mongo as db } from '@cwqt/refract'; 287 | 288 | // Creating a compound index 289 | model 290 | .Field('id', Int(Id, Default('autoincrement()'))) 291 | .Field('authorId', Int()) 292 | .Relation('author', ManyToOne(User, Fields('authorId'), References('id'))) 293 | .Block(Compound.Id('id', 'authorId')); 294 | 295 | // e.g. in MongoDB schemas 296 | Model('User') 297 | .Field('id', String(Id, db.ObjectId, Map('_id'))) 298 | .Block(Compound.Map('users')); 299 | ``` 300 | 301 | # Mixins 302 | 303 | Allows you to re-use groups of fields, compositional models. 304 | 305 | ```typescript 306 | const Timestamps = Mixin() 307 | .Field('createdAt', DateTime(Default('now()'))) 308 | .Field('updatedAt', DateTime(Nullable, UpdatedAt)); 309 | 310 | const User = Model('User').Field('id', PrimaryKey).Mixin(Timestamps); 311 | 312 | // User will now have `createdAt` & `updatedAt` columns 313 | ``` 314 | 315 | ## Programmatic usage 316 | 317 | ```typescript 318 | const prisma = Refract.generate({ 319 | datasource: {...}, 320 | generators: [...], 321 | schema 322 | }) 323 | 324 | console.log(prisma); // schema.prisma contents 325 | ``` 326 | 327 | --- 328 | 329 | # Handling circular relationships 330 | 331 | At some point you'll want to split the schema across files, which introduces issues with circular relationships when you're importing for `.Relation()`s in Node 332 | 333 | One way to get around this is to have a file with all the models/enums defined, and have files import those & apply the fields, e.g. 334 | 335 | ```typescript 336 | // models.ts ------------------------------ 337 | const User = Model("User"); 338 | const Post = Model("Posts"); 339 | // ... and all the other Models 340 | 341 | // users.ts ------------------------------ 342 | import { User, Post } from './models' 343 | 344 | User 345 | .Field("id", Int(Id, Default("autoincrement()"))) 346 | .Relation("posts", OneToMany(Post)) 347 | 348 | // posts.ts ------------------------------ 349 | import { User, Post } from './models' 350 | 351 | Post 352 | .Field("id", Int(Id, Default("autoincrement()"))) 353 | .Field("authorId", Int()) 354 | .Relation("author", ManyToOne(User, Fields("authorId"), References("id"))) 355 | 356 | // refract.ts ------------------------------ 357 | import * as schema from './models' 358 | 359 | // IMPORTANT: import the model files which performs the `.Field()`, `.Relation()` 360 | // etc. calls, thereby adding the columns to the models 361 | import "./posts"; 362 | import "./users"; 363 | 364 | Refract({ 365 | datasource: {...}, 366 | generators: [...], 367 | schema 368 | }) 369 | ``` 370 | 371 |
372 | 373 |
374 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------