Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(deps): update prismagraphql/cockroachdb-custom:23.1 docker digest to b6cbbf9 #4504

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version: '3'
services:
cockroach_23_1:
image: prismagraphql/cockroachdb-custom:23.1@sha256:c5a97355d56a7692ed34d835dfd8e3663d642219ea90736658a24840ea26862d
image: prismagraphql/cockroachdb-custom:23.1.13
restart: unless-stopped
command: |
start-single-node --insecure
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,8 @@ impl SequenceFunction {
let mut this = SequenceFunction::default();

for arg in &args.arguments {
println!("arg.value: {:?}", &arg.value);

match arg.name.as_ref().map(|arg| arg.name.as_str()) {
Some("virtual") => this.r#virtual = coerce::boolean(&arg.value, diagnostics),
Some("cache") => this.cache = coerce::integer(&arg.value, diagnostics),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ impl<'a> ScalarFieldPair<'a> {
self.previous.is_none() && self.description().is_some()
}

fn column_type_family(self) -> &'a sql::ColumnTypeFamily {
pub(crate) fn column_type_family(self) -> &'a sql::ColumnTypeFamily {
self.next.column_type_family()
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
//! The `@default` attribute rendering.

use crate::introspection::introspection_pair::{DefaultKind, DefaultValuePair};
use crate::introspection::introspection_pair::{DefaultKind, DefaultValuePair, ScalarFieldPair};
use datamodel_renderer::{
datamodel as renderer,
value::{Constant, Function, Text, Value},
};

/// Render a default value for the given scalar field.
pub(crate) fn render(default: DefaultValuePair<'_>) -> Option<renderer::DefaultValue<'_>> {
pub(crate) fn render<'a>(field: &ScalarFieldPair<'a>) -> Option<renderer::DefaultValue<'a>> {
let default: DefaultValuePair<'a> = field.default();
let field_family_type = field.column_type_family();

let mut rendered = match default.kind() {
Some(kind) => match kind {
DefaultKind::Sequence(sequence) => {
let mut fun = Function::new("sequence");

// 1 is the default value for the "minValue" attribute
if sequence.min_value != 1 {
fun.push_param(("minValue", Constant::from(sequence.min_value)));
}

if sequence.max_value != i64::MAX {
// `i64::MAX` is the default value for the "maxValue" attribute for INT8 sequences;
// `i32::MAX` is the default value for the "maxValue" attribute for INT4 sequences
if (field_family_type.is_bigint() && sequence.max_value != i64::MAX)
|| (field_family_type.is_int() && sequence.max_value != i32::MAX as i64)
{
fun.push_param(("maxValue", Constant::from(sequence.max_value)));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub(crate) fn render(field: ScalarFieldPair<'_>) -> renderer::Field<'_> {
rendered.documentation(docs);
}

if let Some(default) = defaults::render(field.default()) {
if let Some(default) = defaults::render(&field) {
rendered.default(default);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ impl SqlSchemaCalculatorFlavour for PostgresFlavour {
name: format!("prisma_sequence_{}_{}", model.database_name(), field.database_name()),
..Default::default()
};

// if self.is_cockroachdb() && !field.scalar_field_type().is_bigint() {
// sequence.max_value = i32::MAX.into();
// }

let sequence_fn = field_default.ast_attribute().arguments.arguments[0]
.value
.as_function()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@ impl SqlSchemaDifferFlavour for PostgresFlavour {
.schemas
.map(|schema| (schema, schema.describer_schema.downcast_connector_data()));

let sequences = &schemas.previous.1.sequences;
println!("sequences (prev) = {:?}", &sequences);

let sequences = &schemas.next.1.sequences;
println!("sequences (next) = {:?}", &sequences);

let sequence_pairs = db
.all_column_pairs()
.map(|cols| {
Expand All @@ -128,6 +134,10 @@ impl SqlSchemaDifferFlavour for PostgresFlavour {
let next = pair.next.1;
let mut changes: BitFlags<SequenceChange> = BitFlags::default();

// With CockroachDB 23.1, `migrations::cockroachdb::sequence_int4_works` yields:
println!("prev.max_value = {}", &prev.max_value); // 2147483647
println!("next.max_value = {}", &next.max_value); // 9223372036854775807

if prev.min_value != next.min_value {
changes |= SequenceChange::MinValue;
}
Expand Down
23 changes: 15 additions & 8 deletions schema-engine/sql-introspection-tests/src/test_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,6 @@ impl TestApi {
} else if tags.contains(Tags::CockroachDb) {
let (_, q, cs) = args.create_postgres_database().await;

q.raw_cmd(
r#"
SET default_int_size = 4;
"#,
)
.await
.unwrap();

let mut me = SqlSchemaConnector::new_cockroach();

let params = ConnectorParams {
Expand Down Expand Up @@ -146,6 +138,21 @@ impl TestApi {
}
}

// Call this function when you want the SQL `INT` type to always be mapped to the PSL `Int` type.
// On CockroachDB, for instance, `INT` is an alias to `INT8` (rather than `INT4`), which would
// normally be mapped to `BigInt` in PSL.
// This method is especially useful when testing the same assertions against multiple database providers.
pub async fn normalise_int_type(&self) -> Result<()> {
if self.is_cockroach() {
self.database
.raw_cmd("SET default_int_size = 4")
.await
.expect("Failed to alias INT to INT4 on CockroachDB");
}

Ok(())
}

pub fn connection_string(&self) -> &str {
&self.connection_string
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ async fn array_ops(api: &mut TestApi) -> TestResult {

let expected = expect![[r#"
model A {
id BigInt @id @default(autoincrement())
data Int[]
id BigInt @id @default(autoincrement())
data BigInt[]

@@index([data], type: Gin)
}
Expand Down
210 changes: 208 additions & 2 deletions schema-engine/sql-introspection-tests/tests/cockroachdb/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,32 @@ async fn identity_introspects_to_sequence_with_default_settings_v_22_2(api: Test

let expected = expect![[r#"
model myTable {
id Int @id @default(sequence(maxValue: 2147483647))
id Int @id @default(sequence(maxValue: 9223372036854775807))
name String
}
"#]];

expected.assert_eq(&result);
}

#[test_connector(tags(CockroachDb231))]
async fn identity_introspects_to_sequence_with_default_settings_v_23_1(api: TestApi) {
let sql = r#"
CREATE TABLE "myTable" (
id INT4 GENERATED BY DEFAULT AS IDENTITY,
name STRING NOT NULL,

PRIMARY KEY (id)
);
"#;

api.raw_cmd(sql).await;

let result = api.introspect_dml().await.unwrap();

let expected = expect![[r#"
model myTable {
id Int @id @default(sequence())
name String
}
"#]];
Expand Down Expand Up @@ -245,6 +270,11 @@ async fn scalar_list_defaults_work_on_22_2(api: &mut TestApi) -> TestResult {

api.raw_cmd(schema).await;

// Info:
// Column "datetime_defaults" changes in CockroachDb231:
// ```
// datetime_defaults DateTime[] @default(dbgenerated("'{\"''2022-09-01 08:00:00+00''::TIMESTAMPTZ\",\"''2021-09-01 08:00:00+00''::TIMESTAMPTZ\"}'::TIMESTAMPTZ[]")) @db.Timestamptz
// ```
let expectation = expect![[r#"
generator client {
provider = "prisma-client-js"
Expand Down Expand Up @@ -279,6 +309,60 @@ async fn scalar_list_defaults_work_on_22_2(api: &mut TestApi) -> TestResult {
Ok(())
}

#[test_connector(tags(CockroachDb231))]
async fn scalar_list_defaults_work_on_23_1(api: &mut TestApi) -> TestResult {
let schema = r#"
CREATE TYPE "color" AS ENUM ('RED', 'GREEN', 'BLUE');

CREATE TABLE "defaults" (
id TEXT PRIMARY KEY,
text_empty TEXT[] NOT NULL DEFAULT '{}',
text TEXT[] NOT NULL DEFAULT '{ ''abc'' }',
text_c_escape TEXT[] NOT NULL DEFAULT E'{ \'abc\', \'def\' }',
colors COLOR[] NOT NULL DEFAULT '{ RED, GREEN }',
int_defaults INT4[] NOT NULL DEFAULT '{ 9, 12999, -4, 0, 1249849 }',
float_defaults DOUBLE PRECISION[] NOT NULL DEFAULT '{ 0.0, 9.12, 3.14, 0.1242, 124949.124949 }',
bool_defaults BOOLEAN[] NOT NULL DEFAULT '{ true, true, true, false }',
datetime_defaults TIMESTAMPTZ[] NOT NULL DEFAULT '{ "2022-09-01T08:00Z","2021-09-01T08:00Z"}'
);
"#;

api.raw_cmd(schema).await;

let expectation = expect![[r#"
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "cockroachdb"
url = "env(TEST_DATABASE_URL)"
}

model defaults {
id String @id
text_empty String[] @default([])
text String[] @default(["abc"])
text_c_escape String[] @default(["abc", "def"])
colors color[] @default([RED, GREEN])
int_defaults Int[] @default([9, 12999, -4, 0, 1249849])
float_defaults Float[] @default([0, 9.12, 3.14, 0.1242, 124949.124949])
bool_defaults Boolean[] @default([true, true, true, false])
datetime_defaults DateTime[] @default(dbgenerated("'{\"''2022-09-01 08:00:00+00''::TIMESTAMPTZ\",\"''2021-09-01 08:00:00+00''::TIMESTAMPTZ\"}'::TIMESTAMPTZ[]")) @db.Timestamptz
}

enum color {
RED
GREEN
BLUE
}
"#]];

api.expect_datamodel(&expectation).await;

Ok(())
}

#[test_connector(tags(CockroachDb))]
async fn string_col_with_length(api: &mut TestApi) -> TestResult {
let schema = r#"
Expand Down Expand Up @@ -442,7 +526,7 @@ async fn commenting_stopgap(api: &mut TestApi) -> TestResult {

/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model a {
id Int @id
id BigInt @id
val String? @db.String(20)
}
"#]];
Expand All @@ -461,3 +545,125 @@ async fn commenting_stopgap(api: &mut TestApi) -> TestResult {

Ok(())
}

#[test_connector(tags(CockroachDb231))]
async fn sequences_works_on_23_1(api: &mut TestApi) -> TestResult {
let schema = indoc! {r#"
-- CreateTable
CREATE TABLE "TestModelSeqInt4" (
"id" INT4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,

CONSTRAINT "TestModelSeqInt4_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "TestModelSeqInt8" (
"id" INT8 NOT NULL GENERATED BY DEFAULT AS IDENTITY,

CONSTRAINT "TestModelSeqInt8_pkey" PRIMARY KEY ("id")
);
"#};

api.raw_cmd(schema).await;

let expectation = expect![[r#"
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "cockroachdb"
url = "env(TEST_DATABASE_URL)"
}

model TestModelSeqInt4 {
id Int @id @default(sequence())
}

model TestModelSeqInt8 {
id BigInt @id @default(sequence())
}
"#]];

api.expect_datamodel(&expectation).await;

let expectation = expect![];

api.expect_warnings(&expectation).await;

Ok(())
}

#[test_connector(tags(CockroachDb))]
async fn sequences_works_on_23_1_int8(api: &mut TestApi) -> TestResult {
let schema = indoc! {r#"
-- CreateTable
CREATE TABLE "TestModelSeqInt8" (
"id" INT8 NOT NULL GENERATED BY DEFAULT AS IDENTITY,

CONSTRAINT "TestModelSeqInt8_pkey" PRIMARY KEY ("id")
);
"#};

api.raw_cmd(schema).await;

let expectation = expect![[r#"
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "cockroachdb"
url = "env(TEST_DATABASE_URL)"
}

model TestModelSeqInt8 {
id BigInt @id @default(sequence())
}
"#]];

api.expect_datamodel(&expectation).await;

let expectation = expect![];

api.expect_warnings(&expectation).await;

Ok(())
}

#[test_connector(tags(CockroachDb231))]
async fn sequences_works_on_23_1_int4(api: &mut TestApi) -> TestResult {
let schema = indoc! {r#"
-- CreateTable
CREATE TABLE "TestModelSeqInt4" (
"id" INT4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,

CONSTRAINT "TestModelSeqInt4_pkey" PRIMARY KEY ("id")
);
"#};

api.raw_cmd(schema).await;

let expectation = expect![[r#"
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "cockroachdb"
url = "env(TEST_DATABASE_URL)"
}

model TestModelSeqInt4 {
id Int @id @default(sequence())
}
"#]];

api.expect_datamodel(&expectation).await;

let expectation = expect![];

api.expect_warnings(&expectation).await;

Ok(())
}
Loading
Loading